如何实现 TextField 搜索栏来过滤 tableview 值 Swift

How to implement TextField search bar to filter tableview values Swift

我在 ViewController 顶部创建了一个自定义文本字段栏来过滤 UITableView 中的数据值。因为我有一个 JSON 的嵌套类型,所以无法正确地了解如何为它使用过滤器。

数据是分段的,然后是值,并且已经显示在 tableView 中。

型号:

struct SectionList : Codable {

    let title : String?
    var items : [Item]?

}

struct PickListData: Codable {
    let items: [Item]?
}

struct Item : Codable {

    let actionType : Int?
    var textField : String?
    var pickList: [SectionList]?
    var selection: [Item]?
    let selectedValue: [String]?
    let version: Int?
    let masterId: Int?
    let itemValue: String?
}

ViewController代码:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var searchTxt: UITextField!
    @IBOutlet weak var tableView: UITableView!
    var AppData: Item?
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        tableView.delegate = self
        tableView.dataSource = self
        searchTxt.delegate = self
        readDataList()
    }
    func readDataList(){

        if let url = Bundle.main.url(forResource: "list", withExtension: "json") {
            do {

                let data = try Data(contentsOf: url)
                let decoder = JSONDecoder()
                let response = try decoder.decode(PickListData.self, from: data)
                let res = response.items?.filter { [=12=].actionType == 101}
                AppData = res?.first
                print(AppData)
                self.tableView.reloadData()
            } catch {
                print("error:\(error)")
            }
        }

    }

    @IBAction func textSearchChange(_ sender: UITextField) {
        print("search")
    }


}

extension ViewController: UITableViewDelegate, UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return AppData?.pickList?.count ?? 0
        }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return AppData?.pickList?[section].title
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return AppData?.pickList?[section].items?.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        let dic = AppData?.pickList?[indexPath.section].items?[indexPath.row]//.pickList?[indexPath.row].title
            //AppData?[indexPath.section].pickList[indexPath.row].items
        //print(dic)

        cell.textLabel?.text = dic?.textField
        return cell
    }

}

JSON数据:

{
  "items": [
    {
      "actionType": 101,
      "version": 3,
      "pickList": [
        {
          "title": "Sayaç yeri seçimi",
          "items": [
            {
              "textField": "Sayaç Yeri Seçiniz",
              "itemValue": "0"
            },
            {
              "textField": "Sayaç daire girişinde",
              "itemValue": "1"
            },
            {
              "textField": "Sayaç apt. girişinde",
              "itemValue": "2"
            },
            {
              "textField": "Sayaç bodrumda",
              "itemValue": "3"
            },
            {
              "textField": "Sayaç çatı katında",
              "itemValue": "4"
            },
            {
              "textField": "Sayaç bahçede (Müstakil)",
              "itemValue": "5"
            },
            {
              "textField": "Sayaç bina dışında",
              "itemValue": "6"
            },
            {
              "textField": "Sayaç balkonda",
              "itemValue": "7"
            },
            {
              "textField": "Sayaç daire içinde",
              "itemValue": "8"
            },
            {
              "textField": "Sayaç istasyon içinde",
              "itemValue": "9"
            }
          ]
        }
      ]
    }
]
}

更新代码: 但这是错误的我想用 TextField

搜索
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let searchText  = textField.text! + string

        Filterdata = (AppData?.pickList?.filter({(([=14=].title!).localizedCaseInsensitiveContains(searchText))}))!

         if(Filterdata.count == 0){
           isSearch = false
         }else{
           isSearch = true
        }
         self.tableView.reloadData();

         return true
    }

图片:

方法中textSearchChange 您有查询字符串 sender.text。你应该过滤结果 并将其存储到另一个数组中。然后你可以在 tableView 委托中使用 filteredResultArray 。每次你修改 filteredResultArray 你应该重新加载你的 tableView。

//You need to apply action Sent Event is editing changed

@IBAction func actionTextChange(_ sender: UITextField) {
    print("get text -----\(sender.text)")

}

请按照此步骤获取工作解决方案

* 步骤 1 -> 替换结构

    struct SectionList : Codable {
        let title : String?
        var items : [RowItems]?
        mutating func filterData(string: String) {
            self.items = self.items?.filter({ (item) -> Bool in
                if item.textField?.contains(string) == true {
                    return true
                }
                return false
            })
        }
    }

    struct Item : Codable {
        let actionType : Int?
        var pickList: [SectionList]?
        let version: Int?
        mutating func filterData(string: String) {
            guard var tempList = pickList else { return }
            for index in 0..<tempList.count {
                tempList[index].filterData(string: string)
            }
            pickList = tempList
        }
    }

* 步骤 2 -> 再创建一个变量来保存原始数据

    var globalAppData: Item?

* 第 3 步 -> 在解析时为 globalAppData 赋值 json

    let res = response.items?.filter { [=12=].actionType == 101}
    AppData = res?.first
    globalAppData = AppData

* 第 4 步 -> 为文本更改添加观察者

    searchTxt.addTarget(self, action: #selector(textSearchChange(_:)), for: .editingChanged)

* 步骤 5 -> 替换 textDidChange 方法

    @IBAction func textSearchChange(_ sender: UITextField){

        var tempData = globalAppData
        if let text = sender.text, text.isEmpty == false {
        tempData?.filterData(string: text)
        }
        AppData = tempData

        self.tableView.reloadData()
    }

* 可选步骤 6 ->

如果您想要不区分大小写的搜索,请替换此行

    item.textField?.contains(string)

    item.textField?.lowercased().contains(string.lowercased())