【发布时间】:2018-06-28 17:53:53
【问题描述】:
我是 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
}
【问题讨论】:
-
您需要在问题中显示一些相关代码(作为文本)。你在使用 UISearchController 吗?
-
是的@rmaddy,我正在使用
UISearchController -
我已经更新了我的问题 ;)
-
你不是
filtering 任何东西。您必须filter主要array才能仅获取包含搜索文本的项目。并且从不使用text.count > 0检查空字符串。有一个优化的 API:!text.isEmpty
标签: ios swift uitableview uisearchbar