搜索栏不显示搜索结果

时间:2020-10-10 04:03:13

标签: ios swift xcode

我的应用程序中的搜索栏不起作用。香港专业教育学院将问题缩小为方法cellforRowAt。键入单词时无法显示搜索结果。cellforRowAt包含索引路径中已过滤文章的信息。我该如何解决?

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

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //determines what data source should be used when user types

        if isFiltering{

            return filteredArticles?.count ?? 0

    }

        return articles?.count ?? 0



    }

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! NewsTableViewCell

        let news: Articles

        filteredArticles = articles

        if isFiltering{

            news = filteredArticles![indexPath.row]

        }

        else{

            news = articles![indexPath.row]

        }

        cell.authorName.text = filteredArticles?[indexPath.row].author

        cell.headLine.text = filteredArticles?[indexPath.row].title

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

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



        if let dateString = filteredArticles?[indexPath.row].publishedAt,

        let date = indDateFormatter.date(from: dateString){

                   let formattedString = outDateFormtter.string(from: date)

                   cell.timePublication.text = formattedString

               } else {

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

               }

        

               return cell

           }
   

    func updateSearchResults(for searchController: UISearchController) {

        let searchBar = searchController.searchBar

        filterContentForSearchText(searchBar.text!, articles!)

    }

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

        filteredArticles =  articles?.filter({ (article:Articles) -> Bool in

            return article.description.lowercased().contains(searchText.lowercased())

            

        })

        table_view.reloadData()

    }

     

1 个答案:

答案 0 :(得分:0)

您的代码中的问题是return article.description.lowercased().contains(searchText.lowercased()) 行 在这一行中,article.description为您提供了整个对象的描述,并且是NSObjectProtocol的一种方法。

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

因此,代码应更改为return (article.title?.lowercased().contains(searchText.lowercased()) ?? false)

相关问题