如何解决becomeFirstResponder 在 viewWillAppear
我在 UISearchController
中使用了 navigationItem.titleView
。
这里的目标是我可以输入我的搜索词,当我点击搜索时,我将被推送到一个新的 UIViewController
。当我返回上一个 UIViewController
时,我希望 UITextField
键盘可见,光标位于我之前输入的文本旁边。
我在 viewWillAppear
中调用它,但它没有显示键盘。我的 UISearchController
在设计方面进行了更新,我输入的文本可见,但我必须再次点击 UITextField
才能显示键盘和光标。
我也曾在 viewDidAppear
中尝试过,这是相同的体验。
更新:
当我在 viewDidAppear
中调用执行选择器时,键盘为我显示。
这是我尝试过的:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// A check to see if I need to display the keyboard.
if hasSearchedText {
DispatchQueue.main.async {
self.searchController?.searchBar.perform(#selector(self.becomeFirstResponder),with: nil,afterDelay: 0.1)
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// I've tried removing this & moving it to viewDidAppear but same result.
searchController?.isActive = true
searchController?.searchBar.showsCancelButton = true
let textFieldInsideSearchBar = searchController?.searchBar.value(forKey: "searchField") as? UITextField
if let typedValue = UserDefaults.standard.value(forKey: "xyz") as? String {
textFieldInsideSearchBar?.text = typedValue
// resetting this value
UserDefaults.standard.removeObject(forKey: "xyz")
UserDefaults.standard.synchronize()
}
textFieldInsideSearchBar?.tintColor = // color
textFieldInsideSearchBar?.layer.borderColor = // color
textFieldInsideSearchBar?.layer.borderWidth = 2.0
textFieldInsideSearchBar?.layer.cornerRadius = 8.0
textFieldInsideSearchBar?.textColor = // color
textFieldInsideSearchBar?.font = // font
}
解决方法
您需要在下一个运行循环中在 becomeFirstResponder
上调用 search bar
,如下所示:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
DispatchQueue.main.async {
self.searchController.searchBar.becomeFirstResponder()
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。