【问题标题】:Add UISearchBar to UINavigationBar with UIBarButtonItem使用 UIBarButtonItem 将 UISearchBar 添加到 UINavigationBar
【发布时间】:2015-12-01 04:24:52
【问题描述】:

在我的应用程序中,我曾经在表格视图的标题视图中有一个搜索栏。但是,我添加了一个搜索栏按钮项,当用户点击它时,我希望搜索栏在导航栏上显示动画,并且用户应该能够搜索。这有点像 Twitter iOS 应用程序中的搜索栏。这是我的 UISearchController 的代码:

self.searchController = ({
        let controller = UISearchController(searchResultsController: nil)
        controller.searchResultsUpdater = self
        controller.hidesNavigationBarDuringPresentation = true
        controller.dimsBackgroundDuringPresentation = false
        controller.searchBar.sizeToFit()
        //self.tableView.tableHeaderView = controller.searchBar
        self.definesPresentationContext = true
        controller.searchBar.returnKeyType = .Search
        controller.searchBar.delegate = self

        return controller

    })()

这是我的 UINavigationBar 现在的样子:

我该怎么做呢?

【问题讨论】:

  • 我在这里准确回答了这个问题stackoverflow.com/questions/32259863/…
  • @VictorSigler,我看了你对类似问题的回答。我实际上希望我的搜索栏出现在与 uibarbuttonitem 相同的视图控制器中。那么,我将如何在 IBAction 中执行此操作?我已经尝试通过将导航栏的 titleView 设置为 barbuttonitem 方法中的搜索栏来做到这一点,但它不起作用。

标签: ios swift uinavigationcontroller uinavigationbar uisearchbar


【解决方案1】:

你快到了。你需要做四件事:

  1. searchController.hidesNavigationBarDuringPresentation = false
  2. navigationItem.titleView = searchController.searchBar
  3. 隐藏导航栏中当前所有的 UIBarButtonItems
  4. searchController.searchBar.becomesFirstResponder()

也就是说,你设置你的 UISearchController 让它不会隐藏导航栏,因为 UISearchBar 会显示在那里。

然后,当您的 IBAction 运行时,您执行以下操作:

navigationItem.hidesBackButton = true
navigationItem.titleView = searchController.searchBar
navigationItem.rightBarButtonItem = nil
searchController.searchBar.becomeFirstResponder()

这保证了 UISearchBar 在成为第一响应者时将使用整个 UINavigationBar。您还可以获得 UISearchBar 动画,它很好地隐藏了 UIBarButtonItems 的非动画移除。

一旦用户完成搜索,您将需要实现 UISearchBarDelegate(或者如果您更喜欢 UISearchControllerDelegate)以恢复原始导航栏状态。

一个非常重要的细节是,为了让您的 UISearchBar 在 titleView 中可编辑,在推送您的 UISearchBar 时,不能使用 definePresentationContext = true 设置其他视图控制器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多