我尝试在导航栏下添加SearchController.searchBar。

override func viewDidLoad() {
        super.viewDidLoad()
        searchController = UISearchController(searchResultsController: nil)
        searchController.searchResultsUpdater = self
        searchController.searchBar.sizeToFit()
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.delegate = self
        searchController.dimsBackgroundDuringPresentation = false //
        searchController.searchBar.delegate = self
        let SearchFrame = CGRectMake(0,(self.navigationController?.navigationBar.frame.height)!, (self.navigationController?.navigationBar.frame.width)!,searchController.searchBar.frame.height)
        searchController.searchBar.frame = SearchFrame
        self.navigationController?.navigationBar.addSubview(searchController.searchBar)
}

此代码在navigationBar下添加了searchBar,但是searchBar无法检测到用户交互!我无法单击搜索文本输入字段!我做错什么了?

最佳答案

试试这个。这个对我有用

    var SearchFrame : CGRect?
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let searchController = UISearchController(searchResultsController: nil)
        searchController.searchResultsUpdater = self
        searchController.searchBar.sizeToFit()
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.delegate = self
        searchController.dimsBackgroundDuringPresentation = false //
        searchController.searchBar.delegate = self
        SearchFrame = CGRectMake(0,(self.navigationController?.navigationBar.frame.height)!, (self.navigationController?.navigationBar.frame.width)!,searchController.searchBar.frame.height)
        searchController.searchBar.frame = SearchFrame!
        self.navigationController?.navigationBar.addSubview(searchController.searchBar)


    }

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

        var navbarFrame = self.navigationController!.navigationBar.frame
        navbarFrame.size = CGSize(width: navbarFrame.width, height: navbarFrame.height + SearchFrame!.height)
        self.navigationController?.navigationBar.frame = navbarFrame
    }

关于ios - 如何在NavigationBar(UITableView)swift下添加SearchController.searchBar,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37630704/

10-14 21:58