Locking a UISearchBar to the top of a UITableView like Game Center

后端 未结 7 2067
梦毁少年i
梦毁少年i 2020-12-02 06:33

There\'s this cool feature in the UITableViews in Game Center and the search bars they have at their tops. Unlike apps where the search bar is placed in the table header vie

7条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-02 06:45

    In Swift 2.1 and iOS 9.2.1

        let searchController = UISearchController(searchResultsController: nil)
    
            override func viewDidLoad() {
            /* Search controller parameters */
                searchController.searchResultsUpdater = self  // This protocol allows your class to be informed as text changes within the UISearchBar.
                searchController.dimsBackgroundDuringPresentation = false  // In this instance,using current view to show the results, so do not want to dim current view.
                definesPresentationContext = true   // ensure that the search bar does not remain on the screen if the user navigates to another view controller while the UISearchController is active.
    
                let tableHeaderView: UIView = UIView.init(frame: searchController.searchBar.frame)
                tableHeaderView.addSubview(searchController.searchBar)
                self.tableView.tableHeaderView = tableHeaderView
    
            }
            override func scrollViewDidScroll(scrollView: UIScrollView) {
               let searchBar:UISearchBar = searchController.searchBar
               var searchBarFrame:CGRect = searchBar.frame
               if searchController.active {
                  searchBarFrame.origin.y = 10
               }
               else {
                 searchBarFrame.origin.y = max(0, scrollView.contentOffset.y + scrollView.contentInset.top)
    
               }
               searchController.searchBar.frame = searchBarFrame
           }
    

提交回复
热议问题