【发布时间】:2019-06-19 08:05:51
【问题描述】:
我拥有array 模型数据,我将该数据加载到tableview。
我想为tableview 提供搜索功能。我使用文本字段并根据用户输入过滤array 和reload 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
}
【问题讨论】:
-
你的过滤代码在哪里?
-
在过滤之前,您应该始终保留原始数组。
标签: ios swift uitableview filter textfield