【问题标题】:How can I search for an object in an array? [duplicate]如何在数组中搜索对象? [复制]
【发布时间】: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() 是没有用的。

标签: ios arrays swift


【解决方案1】:

您的filter 语法有点偏离。应该是这样的:

searchTools = tools.filter { $0.name == searchText }

这将为您提供所有Tools,其中name 字段等于当前搜索文本(文字比较)。

或者,用,占case sensitivity and other localization issues

searchTools = tools.filter { $0.name.localizedCaseInsensitiveContains(searchText) }

【讨论】:

  • 非常感谢,我的问题没有更多错误消息了;但是:搜索功能不起作用...您认为我的其余代码是否正确,如进一步显示的那样?
  • 还有:如果用户清除搜索栏,是否可以再次显示所有工具?
  • 您展示的内容很好。但是,有很多代码你没有共享。您必须确保在搜索时,所有表格视图方法都从 searchTools 而不是工具返回。
  • 第二个问题:是的。如果搜索文本为空,则不显示或过滤结果。
  • 我刚刚用更多代码更新了帖子;我发现,我必须附加过滤后的项目......这对吗? // 是的,谢谢,我将为此构建一个 if 语句
猜你喜欢
  • 1970-01-01
  • 2014-02-12
  • 2020-12-05
  • 1970-01-01
  • 2012-04-07
  • 1970-01-01
  • 1970-01-01
  • 2015-05-18
  • 1970-01-01
相关资源
最近更新 更多