【问题标题】:TableView Repeating youtube-api resultTableView 重复 youtube-api 结果
【发布时间】:2018-02-11 18:08:48
【问题描述】:

问题是----> TableView 在所有单元格中显示相同的标题和分布

我的项目视图控制器:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableview: UITableView!

    var articles: [Article]? = []

    override func viewDidLoad() {
        super.viewDidLoad()

        fetchArticles()
    }

    func fetchArticles(){
        let urlRequest = URLRequest(url: URL(string: "https://www.googleapis.com/youtube/v3/search?part=snippet&q=horses&type=video&maxResults=10&key=(apiKey)")!)

        let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in

            if error != nil {
                print(error as Any)
                return
            }

            self.articles = [Article]()
            do {
                let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [String : Any]
                let article = Article()
                if let articlesFromJson = json?["items"] as? [[String : Any]] {
                    for item in articlesFromJson {


                        if let snippet = item["snippet"] as? [String : Any],let title = snippet["title"]as? String,let desc = snippet["description"]as? String {
                             article.headline = title
                             article.desc = desc
                            self.articles?.append(article)
                        }
                    }
                  }

                DispatchQueue.main.async {
                    self.tableview.reloadData()

                }    
            }        
        }
 task.resume()   
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "articleCell", for: indexPath) as? ArticleCell

        cell?.title.text = self.articles?[indexPath.row].headline!
        cell?.desc.text = self.articles?[indexPath.row].desc!

        return cell!
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.articles?.count ?? 0
    }

}

Article.Swift:

import UIKit

class Article: NSObject {

    var headline: String?
    var desc: String?
}

**ArticleCell :**

import UIKit

class ArticleCell: UITableViewCell {


    @IBOutlet weak var title: UILabel!
    @IBOutlet weak var desc: UILabel!



    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

问题是----> TableView 在所有单元格中显示相同的标题和分布

【问题讨论】:

  • 你检查过数组内容吗?它们是相同的还是不同的?
  • 他们是不同的:/
  • 在cellforrow方法中,打印(文章)并确认是否相同!
  • 您能分享您获取的文章数据吗?
  • 当我尝试打印文章时,结果是。 [] [, ] [, , , , ] [, , , ] [, , ,

标签: ios swift uitableview youtube-api


【解决方案1】:

只评论这一行

 DispatchQueue.main.async {
                self.tableview.reloadData()

            } 

/并在 for 循环之后添加它
在for循环中插入let article = Article()
/

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableview: UITableView!

    var articles: [Article]? = []

    override func viewDidLoad() {
        super.viewDidLoad()

        fetchArticles()
    }

    func fetchArticles(){
        let urlRequest = URLRequest(url: URL(string: "https://www.googleapis.com/youtube/v3/search?part=snippet&q=horses&type=video&maxResults=10&key=(apiKey)")!)

        let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in

            if error != nil {
                print(error as Any)
                return
            }

            self.articles = [Article]()
            do {
                let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [String : Any]

                if let articlesFromJson = json?["items"] as? [[String : Any]] {
                    for item in articlesFromJson {


                        if let snippet = item["snippet"] as? [String : Any],let title = snippet["title"]as? String,let desc = snippet["description"]as? String {
                           let article = Article()
                             article.headline = title
                             article.desc = desc
                            self.articles?.append(article)
                        }
                    }

                    self.tableview.reloadData()
                  }

                /*DispatchQueue.main.async {
                    self.tableview.reloadData()

                }  */

            }        
        }
 task.resume()   
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "articleCell", for: indexPath) as? ArticleCell

        cell?.title.text = self.articles?[indexPath.row].headline!
        cell?.desc.text = self.articles?[indexPath.row].desc!

        return cell!
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.articles?.count ?? 0
    }

}

【讨论】:

  • 它是一样的:/
  • func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "articleCell", for: indexPath) as? ArticleCell cell?.title.text = self.articles?[indexPath.row].headline!单元格?.desc.text = self.articles?[indexPath.row].desc!返回细胞! }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-02
  • 2014-01-07
  • 2019-05-12
  • 2017-08-27
  • 2018-03-29
  • 1970-01-01
  • 2016-06-04
相关资源
最近更新 更多