【问题标题】:CollectionUIView reload data does not update display after fetching dataCollectionView 重新加载数据在获取数据后不更新显示
【发布时间】:2017-03-04 13:18:50
【问题描述】:

我正在尝试使用 Swift 开发一个 IOS 应用程序。该应用程序是一个从数据库中检索数据并显示的简单应用程序。

问题是我无法显示通过 REST 服务器从数据库中检索到的数据...我问过类似的问题 here

正如我在那里所说,我尝试DispatchQueue.main.async 来执行获取和reloadData()。但它失败了。

当我将异步替换为同步时,它部分工作(第一个屏幕加载时间,它不显示,但之后它显示项目)。

你们能帮我解决这个问题吗?

以下是我的班级代码

import UIKit

class OrderViewController:UIViewController {

    let cartView:UIView = {
        let tableView = UIView()
        tableView.backgroundColor = UIColor.gray
        tableView.translatesAutoresizingMaskIntoConstraints = false
        return tableView
    }()

    var itemView:UIView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()
        edgesForExtendedLayout = []
        view.backgroundColor = UIColor.white
        itemView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(itemView)
        view.addSubview(cartView)
        setupItemView()
        setupCartView()
        let layout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 20, bottom: 10, right: 20)
        //let viewFrame = CGRect(x: view.bounds.minX, y: view.bounds.minY, width: view.bounds.width*2/3, height: view.bounds.height)
        let collectionViewController = ItemcollectionViewController(collectionViewLayout: layout)

        // get rid of black bar underneath navBar
        self.navigationController?.navigationBar.shadowImage = UIImage()
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)

        itemView.addSubview(collectionViewController.view)
    }

    private func setupItemView(){
        itemView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        itemView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        itemView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 2/3).isActive = true
        itemView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
    }

    private func setupCartView() {
        cartView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        cartView.leftAnchor.constraint(equalTo: itemView.rightAnchor).isActive = true
        cartView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1/3).isActive = true
        cartView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
    }
}

获取数据的类:

    import UIKit
import Alamofire
import SwiftyJSON

class ItemcollectionViewController:UICollectionViewController, UICollectionViewDelegateFlowLayout {

    let dateFormat = "yyyy-MM-dd"
    let cellId = "CellId"
    //var categories: [Category]?
    var categories = [Category]()
    let viewOptionVar:ViewOptionBar = {
        let vOV = ViewOptionBar()
        vOV.translatesAutoresizingMaskIntoConstraints = false
        return vOV
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = UIColor.white
        collectionView?.register(ItemCell.self, forCellWithReuseIdentifier: cellId)
        collectionView?.contentInset = UIEdgeInsetsMake(50, 0, self.view.frame.height, self.view.frame.width)
        collectionView?.scrollIndicatorInsets = UIEdgeInsetsMake(50, 0, 0, self.view.frame.width)
        collectionView?.dataSource = self
        collectionView?.delegate = self
        DispatchQueue.global().async {
            Alamofire.request("http://localhost:8080/category/all").responseJSON { (responseData) -> Void in
                switch responseData.result{
                case .success:
                    if let returnedCategories = responseData.result.value as! NSArray? {
                        for element in returnedCategories {
                            let categoryDictionary = element as! NSDictionary
                            let category = Category()
                            category.categoryId = categoryDictionary["categoryId"] as? String
                            category.categoryName = categoryDictionary["categoryName"] as? String
                            category.categoryDescription = categoryDictionary["categoryDescription"] as? String
                            let categoryRegisteredDateString = categoryDictionary["categoryRegisteredDate"] as? String
                            let df = DateFormatter()
                            df.dateFormat = self.dateFormat
                            let categoryRegisteredDate = df.date(from: categoryRegisteredDateString!)!
                            category.categoryRegisteredDate = categoryRegisteredDate
                            self.categories.append(category)
                        }
                        print("After parsing \(self.categories)")
                    }
                case .failure(let error):
                    print("Error while fetching Categories: \(error)")
                }
            }
            DispatchQueue.main.async {
                self.collectionView?.reloadData()
            }
        }
        print(self.categories)
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.categories.count 
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! ItemCell
        cell.category = categories[indexPath.item]
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 111, height: 111)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    private func setupViweOptionBar() {
        view.addSubview(viewOptionVar)
        view.addConstraintsWithFormat(format: "H:|[v0]|", views: viewOptionVar)
        view.addConstraintsWithFormat(format: "V:|[v0(50)]", views: viewOptionVar)
    }
}

【问题讨论】:

    标签: ios swift uicollectionview


    【解决方案1】:

    试试这个。

    var categories = [Category](){
        didSet {
            self.collectionView?.reloadData()
        }
    }
    

    摆脱

    DispatchQueue.main.async {
                self.collectionView?.reloadData()
    }
    

    【讨论】:

    • 屏幕还是空白 :(
    【解决方案2】:

    你的:

    DispatchQueue.main.async {
                    self.collectionView?.reloadData()
                }
    

    似乎在 Alamofire 请求之外。将其移入case .success:

    【讨论】:

    • @J.GS.Han 我只是再次查看了您的代码,我没有快速编写代码,但您在 UIViewController 中添加了 UICollectionViewController。不知道你为什么这样做,你似乎没有正确添加它,你需要将它添加为 childViewController stackoverflow.com/questions/26599858/… 但是,在尝试使用 Alamofire 响应的 collectionView 之前。用一些模型单元试一试,看看是否显示出来。如果我写的没有解决问题,不调试很难看出问题出在哪里
    猜你喜欢
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    • 2021-09-29
    • 2016-06-05
    • 2022-01-02
    相关资源
    最近更新 更多