I want to change the TableView
data according to Textfield
. when a user taps on Textfield
and starts editing it will change the TableView data
accordingly. I saw a lot of examples on but mainly I found about search bar any help would be appreciated. Please note that this is textfield not seacrhbar
You can try
var searchActive : Bool = false
var data = ["San Francisco","New York","San Jose","Chicago","Los Angeles","Austin","Seattle"]
var filtered:[String] = []
textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)),
for: UIControlEvents.editingChanged)
and handle method:
@objc func textFieldDidChange(_ textField: UITextField) {
// filter tableViewData with textField.text
let searchText = textField.text
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.tableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:CellIdentifier1) as! generalTableViewCell
if(searchActive){
cell.titlelb.text = filtered[indexPath.row]
} else {
cell.titlelb.text = data[indexPath.row];
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(searchActive){
return filtered.count
} else {
return data.count
}
}
您可以在视图控制器中实现textFieldDelegate
,然后在委托方法textFieldDidChange
根据您的使用更改表视图数据源,然后重新加载表视图。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.