ios - 将完整的搜索栏添加到导航

标签 ios swift uinavigationcontroller

我正在像这样向我的导航栏添加一个搜索栏

    searchBar.showsCancelButton = false
    searchBar.placeholder = "Search"
    searchBar.delegate = self
    searchBar.enablesReturnKeyAutomatically = true
    self.navigationItem.titleView = searchBar

但是我有条形按钮项有没有办法隐藏它并使搜索栏全长

最佳答案

试试这个代码:

注意:代码更新了 barButton 在 searchBar 处于事件状态时隐藏功能,并在按下取消按钮时返回。

class ViewController: UIViewController,UISearchControllerDelegate, UISearchResultsUpdating, UISearchBarDelegate {

var resultSearchController : UISearchController!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    self.resultSearchController = UISearchController(searchResultsController:  nil)

    self.resultSearchController.searchResultsUpdater = self
    self.resultSearchController.delegate = self
    self.resultSearchController.searchBar.delegate = self
    self.resultSearchController.hidesNavigationBarDuringPresentation = false
    self.resultSearchController.dimsBackgroundDuringPresentation = true
    self.definesPresentationContext = true 

    self.navigationItem.titleView = resultSearchController.searchBar

    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Your Button", style: .plain, target: self, action: #selector(addTapped))

}

func updateSearchResults(for searchController: UISearchController) {

    // You have to implement search delegate method here to make it work.

    if resultSearchController.isActive == true {

        self.navigationItem.rightBarButtonItem = nil
    }  else {       

    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Your Button", style: .plain, target: self, action: #selector(addTapped))
    }
   }


func addTapped() {
    // You can do your stuff here. when your button pressed...
    print("Button Pressed")

   } 
}

输出:

enter image description here

关于ios - 将完整的搜索栏添加到导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40290095/

相关文章:

ios - 将浮点变量作为参数传递

swift - 1 个 View Controller 中数据的不同表示

ios - 跨多个构建目标 iOS 引用应用程序对象

ios - 取消初始化/无效定时器

iOS - 收到推送通知后显示 View

ios - Xcode 8 SiriKit 扩展 - 无法附加到 pid

ios - 应用程序在 iCloud 中存储数据

ios - searchBar 未在 navigationItem 中居中

ios - 当 View 从纵向更改为横向时,调整带有透明孔的层的位置

ios - 使用向下平移关闭 UINavigationController 相对于顶部安全区域调整 UINavigationBar 的大小