2017-08-16 31 views
0

我想在UINavigationController中显示一个UISearchController,当点击UINavigationController的rightbarbuttonitem并再次点击按钮时隐藏它。如何以编程方式显示UINavigationController的leftbarbuttonitem中的UISearchController并在搜索后将其隐藏?

Initially the UINavigationBar will be like this

后来,

The UINavigationBar should look like this, when search is clicked

,并进一步对关闭图标点击后UINavigationBar的应该看起来像image1的。

我使用显示searchcontroller是代码,

func setUpSearchBar(){ 
     self.searchController = UISearchController(searchResultsController: nil) 

     self.searchController.searchBar.showsCancelButton = true 
     var cancelButton: UIButton 

     let topView: UIView = self.searchController.searchBar.subviews[0] as UIView 
     for subView in topView.subviews { 
      if let pvtClass = NSClassFromString("UINavigationButton") { 
       if subView.isKind(of: pvtClass) { 
        cancelButton = subView as! UIButton 

        cancelButton.setTitle("", for: .normal) 
        cancelButton.tintColor = UIColor.blue 
        cancelButton.setImage(UIImage(named:"close"), for: .normal) 
        cancelButton.addTarget(self, action: #selector(pressButton(button:)), for: .touchUpInside) 
       } 
      } 

     } 

     UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSFontAttributeName:UIFont(name:"Futura-Medium", size:20)!,NSForegroundColorAttributeName:UIColor(red: 234/255, green: 234/255, blue: 234/255, alpha: 1.0)] 

     self.searchController.searchResultsUpdater = self 
     self.searchController.delegate = self 
     self.searchController.searchBar.delegate = self 
     self.searchController.hidesNavigationBarDuringPresentation = false 
     self.searchController.dimsBackgroundDuringPresentation = true 
     self.searchController.searchBar.tintColor = UIColor(red: 56/255, green: 192/255, blue: 201/255, alpha: 1.0) 
     self.searchController.searchBar.backgroundColor = UIColor.clear 
     self.searchController.searchBar.barStyle = .black 
     // self.navigationItem.titleView = searchController.searchBar 
     let leftNavBarButton = UIBarButtonItem(customView: self.searchController.searchBar) 
     self.navigationItem.leftBarButtonItem = leftNavBarButton 
     self.searchController.searchBar.becomeFirstResponder() 
    } 
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { 
     self.searchController.searchBar.resignFirstResponder() 
     self.navigationItem.leftBarButtonItem?.isEnabled = false 
     self.navigationItem.leftBarButtonItem?.tintColor = .clear 

    } 
    func pressButton(button: UIButton) { 
     searchEvent.isEnabled = true 

    } 
    func updateSearchResults(for searchController: UISearchController) { 
     print(searchController.searchBar.text) 
    } 

但这个代码显示了导航栏,但取消按钮点击后,是没有得到触发轻触式的事件吗?这是为什么?

+0

回卷。如果您有新问题,请创建一个单独的问题帖子。你通过改变问题来否定答案,对或错。您可以决定接受/赞成答案。 – niton

回答

0

您可以简单地将hidesNavigationBarDuringPresentation属性设置为true,它设法隐藏导航栏并在该区域显示搜索栏。

+0

谢谢!我做了一个小小的修复工作,但我有一个新的问题,你能帮我解决这个问题吗?请检查我更新的问题。 – swiftDevStart

相关问题