问题
I got SearchController to show up with my TableView, this is what is looks like on launch vs when I scroll up:
This is perfect since I want it hidden when not in use. However, after showing it, I can't hide it again by scrolling down. How do I get that functionality?
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchControllerDelegate, UISearchResultsUpdating {
@IBOutlet weak var tableView: UITableView!
func updateSearchResults(for searchController: UISearchController) {
let searchBar = searchController.searchBar
filterContentForSearchText(searchBar.text!)
}
var isSearchBarEmpty: Bool {
return searchController.searchBar.text?.isEmpty ?? true
}
func filterContentForSearchText(_ searchText: String) {
filteredStrings = stockArr.filter { (string: String) -> Bool in
return string.lowercased().contains(searchText.lowercased())
}
tableView.reloadData()
}
var filteredStrings: [String] = []
var searchController : UISearchController!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
let searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search Candies"
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
definesPresentationContext = true
}
}
Edit:
I played around with adding
tableView.tableHeaderView = searchController.searchBar
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.title = "hello"
but it doesn't look like the normal SearchControllers out there (I don't get why I can't make it work like everyone else's seems to be working, it should automatically have this functionality based on what I saw on here http://blog.eppz.eu/swiftui-search-bar-in-the-navigation-bar/)
回答1:
You'd probably have to check for the scroll direction of UITableView
and disable the UISearchController
manually via code. Here's how:
var lastContentOffset: CGFloat = 0 // declare the previous offset for reference
override func viewDidLoad() {
super.viewDidLoad()
//...
searchController = UISearchController(searchResultsController: nil) // remove let
navigationItem.hidesSearchBarWhenScrolling = true
//...
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
navigationItem.searchController = lastContentOffset < scrollView.contentOffset.y ? nil : searchController
}
来源:https://stackoverflow.com/questions/62997798/hide-searchcontroller-again-after-scrolling-down