在開發(fā)過程中,當(dāng)app需要顯示大量用戶的時(shí)候耽装,想要查找到某一個(gè)用戶顯然沒有那么容易愤炸。參考iOS原生的通訊錄我們可以發(fā)現(xiàn),查找用戶可以用searchBar來精確匹配字段掉奄,也可以用sectionIndex來定位一個(gè)范圍规个。
searchBar的代理方法
//當(dāng)按下搜索按鈕時(shí)進(jìn)入這個(gè)方法
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
self.view.endEditing(true)
searchNumAry = NSMutableArray()
let ary:NSArray = userAry as! NSArray
//循環(huán)遍歷(當(dāng)用戶量非常大的時(shí)候就需要用到算法了,不然會(huì)卡線程)
for i in 0 ..< ary.count {
let dic:NSDictionary = ary[i] as! NSDictionary
let str = (dataDic["name"]) as! String
//匹配字段
if (str.range(of: searchBar.text!) != nil) {
//匹配到的用戶下標(biāo)記下來
searchNumAry.add(NSNumber.init(value: i))
}
}
print(searchNumAry)
self.tableview.reloadData()
}
//當(dāng)輸入框字段改變時(shí)進(jìn)入這個(gè)方法
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
//判斷搜索欄輸入框是否有文字
if (searchBar.text == "") {
self.tableview.reloadData()
}
}
下面是sectionIndex的用法
//設(shè)置索引的標(biāo)題
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
if sectionAry.count != 0 {
return sectionAry
} else {
return [""]
}
}
//設(shè)置section的標(biāo)題
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if sectionAry.count != 0 {
if self.searchBar.text == "" {
return sectionAry[section]
} else {
return ""
}
} else {
return ""
}
}
func numberOfSections(in tableView: UITableView) -> Int {
if self.searchBar.text == "" {
if sectionAry.count != 0 {
return sectionAry.count
} else {
return 0
}
} else {
return 1
}
}
實(shí)現(xiàn)了上面的代碼后姓建,在這兩個(gè)方法中做相應(yīng)的判斷修改即可得到想要的效果了
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell