【问题标题】:Search Bar Not Displaying Search Results搜索栏不显示搜索结果
【发布时间】:2021-01-25 02:43:37
【问题描述】:

我的应用程序中的搜索栏无法正常工作。我已将问题缩小到方法 cellforRowAt。输入单词时无法显示搜索结果。 cellforRowAt 包含索引路径中过滤文章的信息。我该如何解决这个问题?

项目链接:https://github.com/lexypaul13/Covid-News.git

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //确定用户类型时应该使用什么数据源

如果是过滤{

返回filteredArticles?.count ?? 0

}

返回文章?。计数?? 0



}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

让 cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as!新闻TableViewCell

让新闻:文章

过滤的文章 = 文章

如果是过滤{

新闻 = 过滤文章![indexPath.row]

}

别的{

新闻 = 文章![indexPath.row]

}

cell.authorName.text = 过滤文章?[indexPath.row].author

cell.headLine.text = 过滤文章?[indexPath.row].title

cell.newsImage.downloadImage(来自:(self.filteredArticles?[indexPath.item].urlImage ?? "nill"))

cell.timePublication.text = filteredArticles?[indexPath.row].publishedAt



如果让 dateString = filtersArticles?[indexPath.row].publishedAt,

让日期 = indDateFormatter.date(来自:dateString){

让 formattedString = outDateFormtter.string(from: date)

cell.timePublication.text = 格式化字符串

} 别的 {

cell.timePublication.text = "----------"

}



返回单元格

}


func updateSearchResults(for searchController: UISearchController) {

让 searchBar = searchController.searchBar

filterContentForSearchText(searchBar.text!,文章!)

}

func filterContentForSearchText(_ searchText:String ,_ category: [文章]){

filtersArticles = 文章?.filter({ (article:Articles) -> Bool in

返回 article.description.lowercased().contains(searchText.lowercased())



})

table_view.reloadData()

}


 

【问题讨论】:

    标签: ios swift xcode


    【解决方案1】:

    代码中的问题是return article.description.lowercased().contains(searchText.lowercased()) 行 在这一行中,article.description 给出了整个对象的描述,是 NSObjectProtocol 的一个方法。

    因此,对于这种情况,您需要知道需要搜索哪个项目才能获得过滤结果。我查看了代码并知道Articles 包含标题作为参数。您可以使用它来过滤您的搜索

    所以代码应该改为return (article.title?.lowercased().contains(searchText.lowercased()) ?? false)

    【讨论】:

    • 你能解释一下为什么我应该描述没有过滤结果。
    • 每个 NSObject 都有一个名为 description 的属性。甚至 UIViewController 的基类也是 NSObject。这个描述实际上定义了有时在该对象的信息内部的内存布局。因此,如果要过滤,则无法使用描述进行过滤,因为它是整个对象信息,而不是对象的标题或完整描述。您可以在控制台中打印描述并自己查看。