当用户向上/向下滚动时,如何隐藏/显示搜索栏?

时间:2019-07-03 07:48:18

标签: swift

我在iOS 9中实现了搜索栏,并将其附加到表视图的标题中。但我不希望在应用启动时看到它。当用户向下滚动时,当用户向上滚动时,搜索栏应会出现并消失。不幸的是,由于我在iOS 9上,我无法将搜索栏附加到navigationItem.searchController属性。是否可以通过某种方式实现this外观/行为?或者至少在用户向上/向下滚动时隐藏/显示它。 Here是完整的源代码,以备您需要。 预先感谢!

searchController.searchBar.delegate = self

    navigationItem.title = navigationItem.title ?? ci("plan_p")

    tableView.rowHeight = 100.0
    tableView.tableHeaderView = searchController.searchBar

    guard let projectId = GlobalState.selectedProjectId, let byProject : Results<Structure> = self.by(projectId: projectId) else {
        return
    }

    if (navigationItem.title != nil) {
        searchController.searchBar.scopeButtonTitles = [String(format: "gesamte %@", ci("project_s")),  String(format: "in %@", navigationItem.title!)]

    }
    searchController.searchResultsUpdater = self
    searchController.obscuresBackgroundDuringPresentation = false
    searchController.searchBar.placeholder = "Suche nach Plan"
    definesPresentationContext = true

应用启动时搜索栏应该不可见,而用户向上/向下滚动时则隐藏/显示

1 个答案:

答案 0 :(得分:0)

使用UIScrollViewDelegate进行检查表视图滚动。

var position : CGFloat = 0

// this delegate is called when the scrollView (i.e your UITableView) will start scrolling
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    self. position = scrollView.contentOffset.y
}

// while scrolling this delegate is being called so you may now check which direction your scrollView is being scrolled to
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if (self. position < scrollView.contentOffset.y) {
        // table scroll up and you can hide your search bar
        print("move up")
    } else if (self. position > scrollView.contentOffset.y) {
        // table scroll down and you can show your search bar
        print("move down")
    } else {
        // do any thing when stop scrolling
        print("didnt move")

    }
}