如何正确加载UIcollectionView数据?

时间:2019-04-02 07:32:59

标签: ios swift uicollectionview

我在collectionView单元格中具有标签和imageView的默认UIImage数组和名称数组。我调用UIcollectionviews函数并更改了label和imageView的默认源后,reloadData()数据将不会更改,除非我将每个单元格从屏幕上滚动并向后滚动以查看数据已更改。

@IBOutlet weak var mycollectionview: UICollectionView!

var castNames = ["", "", "", "", ""]

var collectionviewimages = [UIImage(named: "pic"), UIImage(named: "pic"), UIImage(named: "pic"), UIImage(named: "pic"), UIImage(named: "pic")]

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

    return castNames.count

    }

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: 
    "customcell", for: indexPath) as! MyCollectionViewCell

    cell.Initialize(image: collectionviewimages[indexPath.row]!, name: 
    castNames[indexPath.row])

    return cell
    }
}

通过点击一个按钮,我得到一些Json并进行解析以更改collectionView的默认数据源。更改ot的方式后,我将其称为func:

mycollectionview.reloadData()

2 个答案:

答案 0 :(得分:0)

始终在主线程上使用reload Collectionview。

dispatchQueue.main.async {
   self.mycollectionview.reloadData()
}

答案 1 :(得分:0)

尝试添加此内容:

collectionView.delegate =自我

collectionView.datasource =自我