UITextField losing firstResponder after view appears

只愿长相守 提交于 2021-02-07 12:19:55

问题


I have a UIPageViewController. One page has a single button, and the other page has a UITextField with a button. When the page scrolls to the view with the field, I'd like it to becomeFirstResponder and open the keyboard. Here's what happens:

  • I call [self.locationQuery becomeFirstResponder] ViewController's viewDidAppear method. But it never opens the keyboard.

  • I do the same in viewWillAppear, and it appears briefly, but then is quickly dismissed.

  • If I'm on the page with the text field, and pull the page partway and let it go (without changing pages), self.locationQuery receives focus just fine.

It seems like something else is grabbing firstResponder status from the field, but I haven't the faintest idea what, and why it would only be happening when the page changed (rather than revealed after a failed page turn). Any ideas?

Update

I created a way to crawl the views to see if any other views were, indeed, taking firstResponder (from an answer to this question: Get the current first responder without using a private API). Results:

  • When I explicitly give first responder to the text field, the method reports it has first responder status.

  • When I don't, it returns null.

Now I'm even more confused.


回答1:


I don't really understand the nature of what was causing my issue, but I was able to fix it by wrapping the call in an async dispatch in viewDidAppear:

dispatch_async(dispatch_get_main_queue(), ^{
    MapManualViewController *strongSelf = weakSelf;
    [strongSelf.locationQuery becomeFirstResponder];
});



回答2:


This one stole a few hours from my life. Here is the Swift 3.x implementation.

DispatchQueue.main.async(execute: {() -> Void in
    let strongSelf: MapManualViewController = self
    strongSelf. textField.becomeFirstResponder()
})

I also put it in viewDidAppear



来源:https://stackoverflow.com/questions/21032056/uitextfield-losing-firstresponder-after-view-appears

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!