现在,我已经为具有多个部分的表格视图实现了搜索栏。但是,当我尝试为行变量创建多维数组时,我的代码中出现错误。这是我目前没有错误的代码。
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变量创建多维数组,以便在仍然使用搜索栏的同时,节的每个单元格中都有不同的字符串?
您可以将它们组合在一起,而不是分别创建一个行数组和节数组。如果搜索为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])]()