ios - 如何显示搜索结果,如 iOS“联系人”应用
问题描述
我是新的 iOS 编程。我试图实现我的应用程序看起来像 iOS 联系人应用程序。但我不知道如何实现我想要的。我想让搜索结果看起来像默认的 iOS 应用程序。
看看我到目前为止的尝试:
当我输入一些东西时, dimsBackgroundDuringPresentation 仍然是true
。
这是我的期望:
我想知道这个应用程序如何显示这样的结果。
这是我声明的方式UISearchController
lazy var searchController: UISearchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.hidesNavigationBarDuringPresentation = false
controller.searchBar.sizeToFit()
controller.searchBar.backgroundColor = UIColor.clear
controller.searchBar.placeholder = "Search"
controller.dimsBackgroundDuringPresentation = true
return controller
})()
这是我如何初始化searchBar
到标题部分的tableView
let searchBar = searchController.searchBar
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
searchBar.delegate = self
tableView.tableHeaderView = searchController.searchBar
这是委托的功能UISearchResultsUpdating
func updateSearchResults(for searchController: UISearchController) {
if let count = searchController.searchBar.text?.count {
if count > 0 {
filterArray.removeAll(keepingCapacity: false)
var a = [String]()
a = [searchController.searchBar.text!]
filterArray = a
searchController.dimsBackgroundDuringPresentation = false
tableView.reloadData()
}else {
searchController.dimsBackgroundDuringPresentation = true
filterArray.removeAll(keepingCapacity: false)
filterArray = array
tableView.reloadData()
}
}
}
这是我的tableView
手机的样子
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.isActive {
return filterArray.count
}else {
return array.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
if searchController.isActive {
cell.textLabel?.text = filterArray[indexPath.row]
}else {
cell.textLabel?.text = array[indexPath.row]
}
return cell
}
解决方案
尝试以下选项:
let search = UISearchController(searchResultsController: nil)
self.definesPresentationContext = true
search.dimsBackgroundDuringPresentation = false
navigationItem.searchController = search
navigationItem.hidesSearchBarWhenScrolling = false
尝试我的 repo 中的代码以查看它是否正常工作,只需点击一个 tableview 项目,它将转到第二个控制器,您可以在其中看到搜索栏并点击它以查看这是否是您想要的
推荐阅读
- flutter - 引发了另一个异常:在 _PagesTestWidgetState.initState() 完成之前调用了dependOnInheritedElement()
- c# - MenuItem 以编程方式设置前台,但不在子菜单 WPF 中
- go - 如何将图片转换为image.RGBA?
- javascript - 检索到所有数据后,如何在内部使用 foreach 循环解决嵌套承诺?
- html - 我可以根据字体大小在 H1-H6 标签中进行选择吗?
- javascript - 显示使用 React Native Image Picker 拍摄的照片
- python - TypeError:'int'和'tuple'的实例之间不支持'<'
- c# - C# wpf,如何在 1 秒内更新进度条
- c++ - 为什么在 C++ 中进行强制转换会打印出意想不到的结果?
- python - 如何使用python创建sql db2数据表?