搜索栏 return 按钮

Search Bar return Button

我在表视图中有一个搜索栏,用于在 .csv 文件 (coredata) 中搜索结果。
列表很大,因此用户必须在第一次搜索后向上滚动多次才能到达搜索栏,或者 select 索引栏中的 "A" 字母。
有没有办法在 NavigationBar 中添加一个按钮,以便在用户想要返回到列表开头时显示 searchBar?提前致谢。

    searchController = UISearchController(searchResultsController: nil)
    tableView.tableHeaderView = searchController.searchBar
    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false


   override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sectionTitles[section]
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        //assume a single section after a search
        return (searchController.active) ? 1 : sectionTitles.count
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if searchController.active {
            return searchResults.count
        } else {
            // Return the number of rows in the section.
            let wordKey = sectionTitles[section]
            if let items = cockpitDict[wordKey] {
                return items.count
            }

            return 0
        }
    }

是的,you can add a UIBarButtonItem to your navigation bar where the action you do will

只需将 tableView.tableHeaderView = searchController.searchBar 中的代码替换为 navigationItem.titleView = searchController.searchBar,它会在 NavigationBar 上显示搜索栏。

但是当您 select 搜索栏时,它会向上移动并且可能在屏幕上不可见,因此您可以使用 UISearchBar 而不是 UISearchController。有关详细信息,请查看这些 thread.

这不完全是您问题的答案,但仍然是您快速 return 进入 table 视图顶部问题的解决方案。您可以将 table 视图的 scrollsToTop: -property 覆盖为 return YES。通过这样做,您将使用户能够通过简单地点击状态栏跳转到 table 的顶部。这是许多股票应用程序的标准行为,例如联系人、邮件、Safari 和照片。

请注意,屏幕上只有一个滚动视图/table 视图/集合视图可能 return YES 才能实现此行为。在多个滚动视图的情况下,您可以选择实现 UIScrollViewDelegate -协议的

- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView

回调并动态检查给定的滚动视图是否应响应点击。

尽管这是 Objective-C 方式,但我想您应该能够将概念转移到 Swift。

这种方法有两个优点:

  1. 您不会弄乱您的导航栏。苹果 iOS Human Interface Guidelines 明确建议

    Avoid crowding a navigation bar with additional controls, even if it looks like there’s enough space. In general, a navigation bar should contain no more than the view’s current title, the back button, and one control that manages the view’s contents.

  2. 您将与 OS 的标准行为保持一致。

我不知道如何将用户直接发送到搜索栏,但总有其他方法可以做,你可以做的是:重新加载故事板,然后它将再次显示搜索栏初始状态。看看这个有趣的 post: How do I perform an auto-segue in Xcode 6 using Swift? 也许你可以通过一个简单的动画立即转到另一个 VC 和 return 这样用户就不会注意到这个骗子。 :)