【发布时间】:2020-05-19 19:36:31
【问题描述】:
我正在尝试使用具有多个部分的 tableview 创建搜索过滤器,并在“cell?.textLabel?.text = self .searchArray[indexPath.row].rowTitles”。我该如何解决?最终目标是能够在 tableview 的各个部分中显示 rowTitles。这是我的代码。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
let dataArray = [(sectionTitle: "section 1", rowTitles: ["row 1", "row 2"]),
(sectionTitle: "section 2", rowTitles: ["row 1", "row 2", "row 3"]),
(sectionTitle: "section 3", rowTitles: ["row 1"]),
]
var searchArray = [(sectionTitle: String, rowTitles: [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 searchArray.count
} else {
return dataArray.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell")
if searching {
cell?.textLabel?.text = self.searchArray[indexPath.row].rowTitles
} else {
cell?.textLabel?.text = self.dataArray[indexPath.row].rowTitles
}
return cell!
}
func numberOfSections(in tableView: UITableView) -> Int {
return self.dataArray.count
}
}
extension ViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchArray = dataArray.filter({$0.sectionTitle.lowercased().contains(searchBar.text!.lowercased())} )
searching = true
tableView.reloadData()
}
}
【问题讨论】:
-
另外你应该避免强制展开返回单元格!
标签: ios swift xcode uitableview