【发布时间】: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