Ios 如何根据文本字段中的用户输入筛选数组模型数据
我拥有Ios 如何根据文本字段中的用户输入筛选数组模型数据,ios,swift,uitableview,filter,textfield,Ios,Swift,Uitableview,Filter,Textfield,我拥有数组模型数据,我将该数据加载到表格视图 我想为该tableview创建搜索功能。我获取文本字段,并根据用户输入过滤数组和重新加载表视图 请在下面找到我的密码 在tableview中 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ let model = array[indexPath.row]
数组
模型数据,我将该数据加载到表格视图
我想为该tableview
创建搜索功能。我获取文本字段,并根据用户输入过滤数组
和重新加载
表视图
请在下面找到我的密码
在tableview中
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let model = array[indexPath.row]
if let rate = model.price
{
cell.pricelbl.text = "$" + rate
}
cell.namelbl.text = model.prodName ?? ""
if (indexPath.row % 2 == 0){
cell.uiview.backgroundColor = UIColor.white
} else {
cell.uiview.backgroundColor = UIColor.lightBaground
cell.uiview.layer.cornerRadius = 15
}
}
//Textfield delegate methods.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == searchtextfield
{
var foundItems = [BaseApparel]()
foundItems = self.array.filter { $0.prodName == searchtextfield.text! }
self.array = foundItems
self.searchtableview.reloadData()
}
return true
}
对数据使用两个字段:
array
和filteradarray
默认情况下,数组和filteredArray应相同:
let array : Array<String> = ["1", "2", "3"];
var filteredData = Array<String>() {
didSet{
self.tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
filteredData = array
}
如果用户更改了文本,则更新filteredData并重新加载表:
@objc func textChangedNotification(_ notification: Notification) {
self.filteredData = self.array.filter { $0.prodName == searchtextfield.text! }
}
用于观察文本字段中的文本变化。过滤代码在哪里?在过滤之前,应始终保留原始数组。
@objc func textChangedNotification(_ notification: Notification) {
self.filteredData = self.array.filter { $0.prodName == searchtextfield.text! }
}