becomeFirstResponder 在 vi​​ewWillAppear 中不起作用

becomeFirstResponder does not work in viewWillAppear

我在 navigationItem.titleView 中使用 UISearchController

这里的目标是我可以输入我的搜索词,当我点击搜索时,我将被推送到一个新的 UIViewController。当我 return 到上一个 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
    }

您需要在下一个 运行 循环的 search bar 上调用 becomeFirstResponder,如下所示:

override func viewDidAppear(_ animated: Bool) {
       super.viewDidAppear(animated)

       DispatchQueue.main.async {
           self.searchController.searchBar.becomeFirstResponder()
       }
}