我目前正在尝试通过 UITableView
使用从 API 调用中检索到的动态数据来实现搜索功能。
流程是这样的
- 按右栏按钮项(搜索功能)
- 搜索 Controller 在 TableView 上显示。
- 用户在上面输入一些文本并按下搜索按钮
- Controller 根据用户的搜索执行 API 调用。
- 表格 View 会填充结果。
我看过一些关于如何在 tableView 上实现搜索的示例,我认为我的不一样,因为我手动呈现了搜索 Controller 。在按下搜索按钮之前它不会显示(与示例相反,当 UISearch
被添加到表标题 View 并且当用户点击搜索栏时触发搜索功能。)
所以基本上我有一些问题:
1.- 我的方法对 iOS 友好吗?也许我找不到关于我如何努力实现的资源,因为事实并非如此。
2.- 如果为真,我如何在按下键盘上的搜索按钮后关闭搜索 Controller ?
3.- 如何区分键盘上的搜索按钮或搜索栏上的取消按钮触发的关闭?
到目前为止,这是我的代码:
extension MyTableViewController: UISearchResultsUpdating {
func updateSearchResultsForSearchController(searchController: UISearchController) {
}
}
class MyTableViewController: UITableViewController, UISearchControllerDelegate {
var searchController: UISearchController!
var data = [CoolData]()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "search"), style: .Plain, target: self, action: .SearchTapped)
}
func searchButtonTapped(sender: UIBarButtonItem) {
searchController = UISearchController(searchResultsController: nil)
definesPresentationContext = true
searchController.searchResultsUpdater = self
searchController.delegate = self
searchController.searchBar.translucent = false
searchController.searchBar.barTintColor = UIColor(hexString: BACConstants.color.Yellow)
searchController.searchBar.tintColor = UIColor(hexString: BACConstants.color.Black)
self.presentViewController(searchController, animated: true, completion: nil)
}
}
private extension Selector {
static let SearchTapped = #selector(InvolvedProcessesViewController.searchButtonTapped(_:))
}
最佳答案
假设您正在使用 UITableViewController
,您可以像这样添加一个 UISearchController
:
var shouldShowSearchResults = false
var searchController: UISearchController!
func configureSearchController() {
searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.delegate = self
searchController.searchBar.sizeToFit()
tableView.tableHeaderView = searchController.searchBar
}
然后,实现这两个委托(delegate):UISearchResultsUpdating
、UISearchBarDelegate
// MARK: - UISearchBarDelegate
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
// do your thing
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
// do your thing
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
// do your thing
searchController.searchBar.resignFirstResponder()
}
// MARK: - UISearchResultsUpdating
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchString = searchController.searchBar.text!.lowercaseString
// do your thing..
tableView.reloadData()
}
关于ios - Swift - 关闭搜索 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38776092/