首页 > 解决方案 > 如何将搜索栏集中在 barbutton 点击​​上?

问题描述

当我单击栏按钮时,我正在尝试自动聚焦搜索栏,但它似乎不适用于becomeFirstResponder,请按照 GIF:

例子

我已经尝试过使用becomeFirstResponder但它不起作用,这就是我处理搜索栏的方式:

// MARK: SearchBar Delegate
    @IBAction func showSearchBarAction(_ sender: Any) {
        let searchController = UISearchController(searchResultsController: nil)
        searchController.searchBar.delegate = self
        searchController.searchResultsUpdater = self
        searchController.searchBar.keyboardAppearance = .dark
        searchController.dimsBackgroundDuringPresentation = false
        navigationItem.searchController = searchController
        navigationItem.searchController?.isActive = true
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        navigationItem.searchController?.isActive = false
        self.navigationItem.searchController = nil
    }

所有这些都完美无缺,但自动对焦是我真正想要的,我也无法改变我的设计

解决方案

此代码是解决方案:

例子

这就是我的类声明的样子:

class YourViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate, UISearchControllerDelegate {
// MARK: SearchBar Delegate
    @IBAction func showSearchBarAction(_ sender: Any) {
        let searchController = UISearchController(searchResultsController: nil)
        searchController.delegate = self
        searchController.searchBar.delegate = self
        searchController.searchResultsUpdater = self
        searchController.searchBar.keyboardAppearance = .dark
        searchController.dimsBackgroundDuringPresentation = false
        self.navigationItem.searchController = searchController
        self.navigationItem.searchController?.isActive = true
    }

    func didPresentSearchController(_ searchController: UISearchController) {

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

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        navigationItem.searchController?.isActive = false
        self.navigationItem.searchController = nil
    }

标签: iosswiftiphone

解决方案


推荐阅读