【发布时间】:2021-02-28 20:32:00
【问题描述】:
我创建了一个名为 Tool 的对象,并将其中一些附加到我的 iOS 应用程序的数组中。现在我想搜索其中一些显示在表格视图中。如何在Tool中搜索特定参数?
class Tool {
var name = String()
var type = String()
var status = String()
var id = Int()
init(name: String, type: String, status: String, id: Int) {
self.name = name
self.type = type
self.status = status
self.id = id
}
}
添加项目:
//Toolbox-Filler
var tools: [Tool] = []
var searchTools: [Tool] = []
表格视图:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searching {
return searchTools.count
}else {
return tools.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifer, for: indexPath) as! ToolboxCell
if searching {
cell.descriptionLabel.text = searchTools[indexPath.row].name
cell.typeLabel.text = searchTools[indexPath.row].type
cell.statusLabel.text = searchTools[indexPath.row].status
}else {
cell.descriptionLabel.text = tools[indexPath.row].name
cell.typeLabel.text = tools[indexPath.row].type
cell.statusLabel.text = tools[indexPath.row].status
}
return cell
}
搜索项目:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchTools.append(contentsOf: tools.filter { $0.name == searchText })
searching = true
tableView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searching = false
searchBar.text = ""
tableView.reloadData()
}
这是正确的方法吗? Xcode 在测试时显示错误。
【问题讨论】:
-
注意你的类属性可以声明为
let name: Stringlet id: Int等(如果你希望以后能够更改它们,那么它们可以是var)。将它们冗余初始化为String()和Int()是没有用的。