【问题标题】:How to filter array model data based on user input in text field如何根据文本字段中的用户输入过滤数组模型数据
【发布时间】:2019-06-19 08:05:51
【问题描述】:

我拥有array 模型数据,我将该数据加载到tableview

我想为tableview 提供搜索功能。我使用文本字段并根据用户输入过滤arrayreload 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


【解决方案1】:

对数据使用两个字段:arrayfilteredArray

默认数组和filteredArray应该是一样的:

let array : Array<String> = ["1", "2", "3"];
var filteredData = Array<String>() {
    didSet{
        self.tableView.reloadData()
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    filteredData = array
}

使用filteredData数组产生单元格:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.filteredData.count
    }

如果用户更改了文本,则更新过滤数据和重新加载表:

@objc func textChangedNotification(_ notification: Notification) {
        self.filteredData = self.array.filter { $0.prodName == searchtextfield.text! }
    }

使用textDidChangeNotification 观察文本字段中的文本变化。

【讨论】:

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