简体   繁体   English

防止 UISearchBar 在 UITableView 中滚动时隐藏(滚动时保持 UISearchBar 显示)-Swift,Xcode

[英]Prevent UISearchBar from Hiding when scrolling in UITableView (Keep UISearchBar shown when scrolling) - Swift, Xcode

I currently have a UISearchBar (code below) which works fine however I'm trying to make it so upon scrolling in my UITableView, my UISearchBar does not disappear.我目前有一个 UISearchBar(下面的代码),它工作正常,但是我试图让它在我的 UITableView 中滚动时,我的 UISearchBar 不会消失。 One of the things I've read is to embed a searchController into a view controller with the following line of code: navigationItem.searchController = yourSearchController and then to prevent the UISearchBar from hiding, add this line of code: navigationItem.hidesSearchBarWhenScrolling = false however it has not worked.我读过的一件事是使用以下代码行将 searchController 嵌入到视图控制器中: navigationItem.searchController = yourSearchController然后为了防止 UISearchBar 隐藏,添加这行代码: navigationItem.hidesSearchBarWhenScrolling = false但是它没有奏效。 I've also read to put the SearchBar above the UITableView in the View Hierarchy, but when I do that and place it below the Navigation Bar, upon scrolling it overlaps the tableView cells.我也读过将 SearchBar 放在 View Hierarchy 中的 UITableView 上方,但是当我这样做并将其放在导航栏下方时,滚动时它会与 tableView 单元格重叠。 Do I need a SearchController, and if so, how do I implement this?我是否需要 SearchController,如果需要,我该如何实现? I've spent hours searching through similar StackOverflow threads with the same question asked many years ago and have attempted to implement the responses, however, none of the responses have worked.我花了几个小时在类似的 StackOverflow 线程中搜索多年前提出的相同问题,并尝试实现响应,但是,没有一个响应有效。 Any response would be greatly appreciated, thanks!任何回应将不胜感激,谢谢!

UISearchBar IBOutlet: UISearchBar IBOutlet:

@IBOutlet weak var searchBar: UISearchBar!

viewDidLoad Func: viewDidLoad 函数:

filteredData = data

UISearchBar Code: UISearchBar 代码:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
   if searchText.isEmpty {
      filteredData = data
   } else {
      filteredData = data.filter{$0.title.range(of: searchText, options: .caseInsensitive) != nil }
   }
   self.tableView.reloadData()
}
}

View Hierarchy:查看层次结构:

View Controller Layout:视图控制器布局:

What if you create a UISearchController as a variable:如果您创建一个 UISearchController 作为变量会怎样:

let searchController = UISearchController(searchResultsController: nil)

and then on viewDidLoad然后在 viewDidLoad

navigationItem.titleView = searchController.searchBar 

The difference here is that your seachBar is embedded on the title of the navigationItem, so it won't disappear on scrolling.这里的区别在于您的 seachBar 嵌入在导航项的标题上,因此它不会在滚动时消失。 This shows the behavior you are looking for.这显示了您正在寻找的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM