0
我使用UISearchBar搜索地址簿&顯示結果。Swift3 UISearchBar不能正常工作
在我的地址簿,還有凱特·貝爾,安娜·阿羅,丹尼爾·希金斯等
首先嚐試:「凱特鍾」顯示我的權利。
第二個嘗試: 「安娜哈羅」 顯示我凱特&安娜。
然後第三次嘗試:「丹尼爾·希金斯」 ......從這一刻起的UISearchBar不能給我正確的結果....
我不知道是什麼問題&如何解決這個....
我在下方附上我的SWIFT代碼..
var searchActive : Bool = false
var data:[String] = []
var filtered:[String] = []
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
friendsTableView.delegate = self
friendsTableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(searchActive) {
return filtered.count
}
return contacts.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : ContactTableViewCell = tableView.dequeueReusableCell(withIdentifier: "ContactTableViewCell", for: indexPath) as! ContactTableViewCell
let cell2 = tableView.dequeueReusableCell(withIdentifier: "ContactTableViewCell")! as UITableViewCell;
let entry = contacts[(indexPath as NSIndexPath).row]
cell.configureWithContactEntry(entry)
cell.layoutIfNeeded()
if(searchActive){
cell2.textLabel?.text = filtered[indexPath.row]
} else {
cell2.textLabel?.text = data[indexPath.row]
}
return cell
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchActive = true;
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchActive = false;
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchActive = false;
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchActive = false;
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filtered = data.filter({ (text) -> Bool in
let tmp: NSString = text as NSString
let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
return range.location != NSNotFound
})
if(filtered.count == 0){
searchActive = false;
} else {
searchActive = true;
}
self.friendsTableView.reloadData()
}
小區2不會從'cellForRowAt'返回 – Magnas
@Magnas感謝您的回覆!但我沒有進入你的身體......你能解釋一下嗎? –
在'tableView:cellForRowAt:'你創建'cell'並且你也創建'cell2'你返回'cell',但是你對'cell2'沒有做任何事情 – Magnas