【问题标题】:Creating a search bar for a table view that has multiple sections为具有多个部分的表视图创建搜索栏
【发布时间】:2020-09-04 19:59:27
【问题描述】:

现在我已经为具有多个部分的表格视图实现了一个搜索栏。但是,当我尝试为我的 rows 变量创建一个多维数组时,我的代码中出现错误。这是我目前没有错误的代码。

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var tableView: UITableView!

    var rows: [String] = ["row 1", "row 2", "row 3"]
    var sections: [String] = ["section 1", "section 2", "section 3"]
    var search = [String]()
    var searching = false

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
    }
}

extension ViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if searching {
            return search.count
        } else {
            return rows.count
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell")
        if searching {
            cell?.textLabel?.text = search[indexPath.row]
        } else {
            cell?.textLabel?.text = rows[indexPath.row]
        }
        return cell!
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }

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

extension ViewController: UISearchBarDelegate {
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        search =  rows.filter({$0.lowercased().prefix(searchText.count) == searchText.lowercased()})
        searching = true
        tableView.reloadData()
    }
}

如何为我的 rows 变量创建一个多维数组,以便在仍然使用搜索栏的同时在一个部分的每个单元格中有不同的字符串?

【问题讨论】:

    标签: ios swift uitableview multidimensional-array uisearchbar


    【解决方案1】:

    您可以将它们组合在一起,而不是单独创建行数组和节数组。当搜索为 false 时,显示 dataArray 的数据。当用户搜索时,将结果附加到 searchArray 并在 tableView 中显示。我建议您先观看一些 YouTube 视频,然后再推进您的应用程序。祝你好运!

    let dataArray: [(sectionTitle: String, rowTitles: [String])] = [
        (sectionTitle: "section1", rowTitles: ["item1", "item2"]),
        (sectionTitle: "section2", rowTitles: ["item1", "item2", "item3"]),
        (sectionTitle: "section3", rowTitles: ["item1", "item3"]),
    ]
    
    let searchArray = [(sectionTitle: String, rowTitles: [String])]()
    

    【讨论】:

      猜你喜欢
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 2018-10-02
      相关资源
      最近更新 更多