问题描述
我的应用程序有一个模态视图控制器,包括一个搜索栏.当视图出现时,我希望搜索栏聚焦.我在viewDidLoad
中尝试了[self.searchBar becomeFirstResponder]
,但是没有用.后来我将其放在viewDidAppear
中,它起作用了.但是,使用此替代方法,会有明显的延迟. (视图完全显示后,键盘开始出现)
My Application has a modal view controller, including a search bar. When the view comes up, I want the search bar to be focused. I tried [self.searchBar becomeFirstResponder]
in viewDidLoad
, but it didn't work. Later on I put it in viewDidAppear
, it worked. But with this workaround, there is a visible delay. (after the view fully appeared, the keyboard began to appear)
我可以确保同时调用viewDidAppear
和viewDidLoad
.
I can ensure both viewDidAppear
and viewDidLoad
have been invoked.
如果我希望搜索栏在显示视图时立即聚焦,该怎么办?
What should I do if I want the search bar to be focused instantly with the view appear?
(我正在使用StoryBoard)
(I'm using StoryBoard)
按照答案,我尝试将代码放入viewWillLoad
,但仍然无法正常工作. (在viewWillLoad
中,self.searchBar.window
为零)
Followed the answers, I tried to put the code in viewWillLoad
, but still didn't work. (in viewWillLoad
, self.searchBar.window
is nil)
推荐答案
您应该在viewDidLayoutSubviews()中调用,以下设置textField的代码仅在第一次查看布局子视图时才成为FirstResponder,应该是.
You should call in viewDidLayoutSubviews(), the code below set textField becomeFirstResponder only at the first time view layout subviews, and it should be.
var isFirstLayout: Bool = true
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if isFirstLayout {
defer { isFirstLayout = false }
textField.becomeFirstResponder()
}
}
这篇关于成为firstResponder在viewDidAppear中工作,但在viewDidLoad中不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!