【问题标题】:How to implement TextField search bar to filter tableview values Swift如何实现 TextField 搜索栏来过滤表视图值 Swift
【发布时间】:2020-05-28 04:06:33
【问题描述】:

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

  • 我想将textField 实现为带有TableView 的搜索栏。附上屏幕截图。
  • 我需要过滤的值是pickList -> textField
  • 为文本搜索添加了textSearchChange 功能。

数据是分段的,然后是值,并且已经显示在 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 { $0.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({(($0.title!).localizedCaseInsensitiveContains(searchText))}))!

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

         return true
    }

图片:

【问题讨论】:

    标签: ios swift uitableview uitextfield uisearchcontroller


    【解决方案1】:

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

    【讨论】:

    • 谢谢,是的,我试过这样但没有用。 tableFilterdata = [AppData!] 然后Filterdata = tableFilterdata.filter({($0.textField?.contains(searchTxt.text!))!})
    • 修改filteredData后应该重新加载tableView
    【解决方案2】:

    //你需要应用action Sent Event is editing changed

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

    【讨论】:

    • 谢谢 是的这个东西我已经完成了那个设置outlet Event
    【解决方案3】:

    请按照此步骤获取有效的解决方案

    * 第 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 步 -> 在解析 json 时为 globalAppData 赋值

        let res = response.items?.filter { $0.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())
    

    【讨论】:

    • 老实说,它是如此完美的解决方案,虽然有点复杂,但运行顺畅。非常感谢,但这也是以这种方式使用 struct 的一个很好的学习。
    • 但是,只要您有时间,请务必解释mutating func 的概念。谢谢。
    • 有这样的cmets真是太好了。当然我会解释的。
    猜你喜欢
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多