[英]How to implement TextField search bar to filter tableview values Swift
我在 ViewController 頂部創建了一個自定義 textField 欄來過濾UITableView
數據值。 由於我有嵌套類型的 JSON,因此無法正確了解如何為其使用過濾器。
textField
實現為搜索欄。 附上截圖。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?
}
視圖控制器代碼:
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
}
請按照以下步驟操作以獲得工作解決方案
* 第 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())
在textSearchChange
方法中,您有查詢字符串sender.text
。 您應該過濾結果並將其存儲到另一個數組中。 然后您可以在 tableView 委托中使用filteredResultArray
結果數組。 每次修改filteredResultArray
都應該重新加載tableView。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.