我试图在按下UISearchController按钮时添加UINavigationBar。当再次按下按钮时,它会关闭搜索栏。到目前为止我有:

@IBAction func showSearchBar(sender: UIBarButtonItem) {
    if searchController == nil {
        var resultsController = SearchResultsViewController()
        resultsController.searchResultsDelegate = self

        searchController = UISearchController(searchResultsController: resultsController)
        searchController!.searchResultsUpdater = resultsController

        searchController!.searchBar.frame = CGRect(
            x: searchController!.searchBar.frame.origin.x,
            y: searchController!.searchBar.frame.origin.y,
            width: searchController!.searchBar.frame.size.width,
            height: 44.0)
        searchController!.searchBar.center.x += self.view.bounds.width
    }

    if !searchBarActive {
        UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
            self.searchController!.searchBar.center.x -= self.view.bounds.width
        }, completion: nil)
        searchController?.hidesNavigationBarDuringPresentation = false
        searchController?.searchBar.searchBarStyle = UISearchBarStyle.Default
        searchController?.dimsBackgroundDuringPresentation = true
        navigationItem.titleView = searchController?.searchBar
        self.definesPresentationContext = true

    } else {
        UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
            self.searchController!.searchBar.center.x += self.view.bounds.width
        }, completion: nil)
        dismissViewControllerAnimated(true, completion: nil) // edited: tried this per comments but also does not work
        searchController!.active = false
    }

    searchBarActive = !searchBarActive
}

这将添加searchController.searchBar并从屏幕的右侧将其滑入。再次按下该按钮时,搜索栏会向右滑动。但是,搜索栏上的“我的后退”按钮不会重置为“后退”,当我将navitionItem滑出屏幕时,原来的标题也不会返回。我觉得我错过了一些东西,以便消除searchBar,但我不知道什么是正确的调用。searchController.active属性似乎不起作用。

最佳答案

调用dismissViewControllerAnimated:关闭UISearchController并在方法的完成块中执行所有其他更改。

关于ios - 不事件时从UINavigationBar移除UISearchController,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30159794/

10-12 13:28