【问题标题】:Reloading UICollection view after data parse数据解析后重新加载 UICollection 视图
【发布时间】:2017-05-30 11:38:15
【问题描述】:

我正在尝试动态更新 uicollectionview。我使用this amazing tutorial 来了解如何创建一个简单的 uicollection。

在使用静态项目数组时效果很好。我的问题 - 我想让 uicollection 填充我从数据库解析到新数组的数据。在解析我的 json 数据后,我不确定如何重新加载 uicollection。

更新后的代码:

import UIKit

class Books: UIViewController, UICollectionViewDelegate {

    @IBOutlet weak var bookscollection: UICollectionView!

    var user_id: Int = 0;

    //------------ init ---------------//

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func viewDidAppear(_ animated: Bool) {
        showtutorial()
        getuserid()
    }


    //------------ show books ---------------//

    var booknames = [String]()
    var bookcolor = [String]()
    var bookdescription = [String]()
    var bookid = [Int]()

    func posttoapi(){

        //show loading
        LoadingOverlay.shared.showOverlay(view: self.view)

        //send
        let url:URL = URL(string: "http://www.url.com")!
        let session = URLSession.shared
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
        let paramString = "user_id=\(user_id)"
        request.httpBody = paramString.data(using: String.Encoding.utf8)

        let task = session.dataTask(with: request as URLRequest) {(data, response, error) in

            //hide loading
            LoadingOverlay.shared.hideOverlayView()

            //no response
            guard let data = data, let _:URLResponse = response, error == nil else {
                print("response error")
                return
            }

            //response, parse and send to build
            let json = String(data: data, encoding: String.Encoding.utf8);
            if let data = json?.data(using: String.Encoding.utf8){

                let json = try! JSON(data: data)

                for item in json["rows"].arrayValue {

                    //push data to arrays
                    self.booknames.append(item["name"].stringValue)
                    self.bookcolor.append(item["color"].stringValue)
                    self.bookdescription.append(item["description"].stringValue)
                    self.bookid.append(item["id"].int!)

                    //reload uicollection 
                    DispatchQueue.main.sync(execute: {
                        self. bookscollection.reloadData()  
                    })


                }

            }

        }

        task.resume()

    }




    //------------ collection -------------//

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        print("collection view code called")
        return self.booknames.count
    }


    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = bookscollection.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! BooksCell
        cell.myLabel.text = self.booknames[indexPath.item]
        cell.backgroundColor = UIColor.cyan // make cell more visible in our example project
        return cell
    }


    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.item)!")
    }



    //------------ end ---------------//

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


}

感谢您的帮助!

【问题讨论】:

  • 你需要证明JSON解析代码
  • 您是否为 collectionView 创建了 outlet,然后请同时显示该代码。
  • @andehlu 从数据库中获取数据或获取 json 响应任何涉及一些耗时的任务的东西都应该在后台工作,更新用户界面应该在主线程上工作,所以使用调度队列在主线程上重新加载数据线程。
  • 感谢@TusharSharma,因为我在 DispatchQueue.main.sync(execute: { self.collectionView.reloadData() }) 下面仍然没有摆脱 self.collectionView 上的模棱两可的引用错误...有什么想法吗?
  • @andehlu 你能更新问题并显示错误的内容和位置吗?

标签: ios arrays swift2 uicollectionview xcode8


【解决方案1】:

我遇到了同样的问题..你的网址有很多图片意味着重新加载 t

dispatch_async(dispatch_get_main_queue(), {
    self.collectionView.reloadData()
})

【讨论】:

  • 正确答案!
  • 如果正确答案意味着请打勾@andehlu
  • 实际上,一旦我有插座,这确实有效。谢谢。
猜你喜欢
  • 1970-01-01
  • 2017-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 1970-01-01
相关资源
最近更新 更多