1.在storyboard里面拖入一个 Search Bar 和 一个 tableView。
2.创建ViewController,实现代理:UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate.
代码实现如下:
@IBOutlet weak var searchCt: UISearchBar!
var contacts = [Contact] ()
// 搜索匹配的结果,Table View使用这个数组作为datasource
var seres:[Contact] = []
override func viewDidLoad() {
super.viewDidLoad()
self.searchCt.showsCancelButton = false;
self.searchCt.delegate = self
self.tableView.delegate = self
self.tableView.dataSource = self
seres = contacts
}
// tableview 代理方法
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.result.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identify: String = "cell"
let cell = tableView.dequeueReusableCellWithIdentifier(identify, forIndexPath: indexPath) as UITableViewCell
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
cell.textLabel?.text = self.seres[indexPath.row]
return cell
}
// UISearchBar 代理方法
// 每次改变搜索内容时候调用此方法
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchCt.showsCancelButton = true;
}
// 搜索代理UISearchBarDelegate方法,每次改变搜索内容时都会调用
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
//print(searchText)
// 没有搜索内容时显示全部组件
if searchText == "" {
self.seres = self.contacts
}
else { // 匹配用户输入内容的前缀(不区分大小写)
self.seres = []
for tmp in self.contacts {
if (tmp.name?.lowercased().hasPrefix(searchText.lowercased()))! {
self.seres.append(tmp)
}
}
}
// 刷新Table View显示
self.tableView.reloadData()
}
/*
// 搜索代理UISearchBarDelegate方法,点击虚拟键盘上的Search按钮时触发
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
*/
// 取消按钮触发事件
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchCt.showsCancelButton = false;
searchCt.text = ""
self.seres = self.contacts
searchCt.resignFirstResponder()
self.tableView.reloadData()
}
- 版权声明:本文基于《知识共享署名-相同方式共享 3.0 中国大陆许可协议》发布,转载请遵循本协议
- 文章链接:http://www.carlstedt.cn/archives/1391 (转载时请注明本文出处及文章链接)


发表评论
快来吐槽一下吧!