【问题标题】:How to filter array of dictionary data on based on user input in textfield如何根据文本字段中的用户输入过滤字典数据数组
【发布时间】:2019-06-19 11:29:08
【问题描述】:

您好,我使用array 模型数据,我将该数据加载到tableview

但我想根据textField 中的用户输入搜索该数据

  • 代码。
     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 ?? ""
      }

    //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
        }

【问题讨论】:

  • 有什么问题
  • 当我尝试在文本字段中输入文本时,它不会在 tableview 中显示任何数据。
  • 设置委托和数据源
  • 你用搜索栏搜索了吗
  • 不,我使用文本字段

标签: ios arrays swift dictionary tableview


【解决方案1】:

使用谓词: 在 viewDidLoad() 中,添加以下行

searchtextfield.addTarget(self, action: #selector(valueDidModify(_:)), for: .editingChanged)

然后使用这个函数:

@objc func valueDidModify(_ sender:UITextField){
      let predicate =  NSPredicate(format:"self.prodName CONTAINS [cd] %@",sender.text)
      let filteredArray = self.array.filter{predicate. evaluateWithObject($0)}
     }

将 numberOfRows 返回为 filteredArray.count

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    • 2021-09-21
    • 2021-12-18
    • 2011-08-30
    • 1970-01-01
    • 2022-10-15
    相关资源
    最近更新 更多