首页 > 解决方案 > 表格视图单元格不显示相应的网站

问题描述

我创建了一个 Web 视图来在表格视图控制器上显示数据;但是,表格视图单元格不显示从 newsapi.com 检索到的相应 URL 链接。如何解决此问题以使其在选择单元格时显示正确的网站?项目链接:https ://github.com/lexypaul13/Covid-News

extension LatestNewsViewController: UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if isFiltering{
            return filteredArticles?.count ?? 0
        }
        return news.articles?.count ?? 0
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! NewsTableViewCell
        
        var articleToUse = news.articles
        
        if isFiltering{
            articleToUse = news.articles
        }
        
        cell.authorName.text = articleToUse?[indexPath.row].author
        cell.headLine.text = articleToUse?[indexPath.row].myDescription
        //         cell.newsImage.downloadImage(url:(row?.urlImage ?? "nill"))
        if let dateString = articleToUse?[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 tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.urlSelected = newsSelected?[indexPath.row].urlWebsite ?? ""
    }
    
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "article"{
            if table_view.indexPathForSelectedRow != nil{
                let destinationController = segue.destination as! ArticleViewController
                destinationController.url = self.urlSelected
            }
        }
    }
  
class ArticleViewController: UIViewController {

    @IBOutlet weak var articlePage: WKWebView!
    
    
    var url : String =  "http://newsapi.org/v2/everything?q=coronavirus&sortBy=popularity&apiKey=d32071cd286c4f6b9c689527fc195b03&pageSize=50&page=2"
    
    override func viewDidLoad() {
       
        super.viewDidLoad()
        if let url = URL(string: url ) {
        let request = URLRequest(url: url)
            articlePage.load(request)
        // Do any additional setup after loading the view.
    }
}

标签: iosswift

解决方案


您在用于 tableView 的 3 种方法之间不一致。

  • numberOfRowsInSection中,您使用filtersArticlesnews.articles
  • cellForRowAt你只使用news.articles
  • 而在didSelectRowAt,您使用newsSelected设置为惰性 var,因此只设置一次并且永远不会更新。

更好地使用filteredArticlesnews.articles以同样的方式为这3 种方法


推荐阅读