Swift SearchBar 过滤和更新多个数组

Swift SearchBar Filtering & Updating Multiple Arrays

我需要实现一个 searchBar 来搜索和过滤带有 2 个标签的 tableview。标签数据来自 2 个不同的数组。因此,当我通过数组 1/标签 1 进行过滤时,它会过滤但标签 2 保持不变,因此结果是混合的。两个数组都是在 SQL 查询结果后创建的,有 2 列数据。我的意思是 arr1[0] 和 arr2[0] 是同一行但不同的列。经过太多尝试,我被困住了。这是最新的代码:

var arr1 = [String]()
var arr2 = [String]()
var filtered:[String] = []

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if(searchActive) {
        return filtered.count
    } else {
        return arr1.count
    }
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> xxTableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "xxCell", for: indexPath) as! xxTableViewCell

    if(searchActive){

        cell.label1.text = filtered[(indexPath as NSIndexPath).row]

    } else {

        cell.label1.text = arr1[(indexPath as NSIndexPath).row]
        cell.label2.text = arr2[(indexPath as NSIndexPath).row]

    }
    return cell
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    filtered = arr1.filter({ (text) -> Bool in
        let tmp: NSString = text as NSString
        let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
        return range.location != NSNotFound
    })
    if(filtered.count == 0){
        searchActive = false;
    } else {
        searchActive = true;
    }


    self.tableView.reloadData()
}

问题:searchActive = true 时,您在 cellForRow 中没有 label2.text 的值。因此,每当您在过滤器后重新加载 tableView 时,都会更新 label1.

的新值

解法:

像这样修改你的代码。

if(searchActive){

    cell.label1.text = filtered[(indexPath as NSIndexPath).row]
    cell.label2.text = @"" //assign value to label2 after filter 
} else {

    cell.label1.text = arr1[(indexPath as NSIndexPath).row]
    cell.label2.text = arr2[(indexPath as NSIndexPath).row]

}

如果arr1[] 和arr2[] 是单行数据的两列,那么您应该有一个数组。有很多方法可以做到这一点——元组、classes、结构——但我倾向于选择结构。如果你有额外的处理,你会想要执行它可以更好地实现为 class,但同样的原则适用。

定义你需要的结构

struct MyDataStruct
{
    var label1 : String = ""
    var label2 : String = ""
}

然后定义一个这种类型的数组(而不是arr1,arr2)

var myData = [MyDataStruct]()

然后像以前一样构建数据和搜索数组 - 但进入这个单一结构

myData.append(MyDataStruct(label1: "Hello", label2: "World"))

最后一步在 tableView 方法中

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> xxTableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "xxCell", for: indexPath) as! xxTableViewCell

    if(searchActive){
        cell.label1.text = filtered[indexPath.row].label1
    } else {
        cell.label1.text = myData[indexPath.row].label1
        cell.label2.text = myData[indexPath.row].label2 
    }
    return cell
}