swift - 无法将项目附加到 CollectionView

标签 swift collectionview

我在 UIViewController 中使用 CollectionView,这个 CollectionView 使用 PinterestLayout。我现在已经有 10 件商品(1 件是“+”图片,9 件是礼物图片)。当我单击此 saveButton 以再添加一个 Gift 时:

enter image description here

它不会加载“Torres”图像。

enter image description here

这是我在 saveButton 操作中的代码:

func saveButtonTapped(sender: AnyObject) {
        addViewIsShowed = false
        let caption = addView.addTextView.text
        let image = addView.addImageView.image!
        let gift = Gift(caption: caption, image: image.decompressedImage)
        // gifts.count is 10
        gifts.append(gift)
        // gifts.count is now 11
        addView.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
        collectionView.alpha = 1.0
        saveButton!.removeFromSuperview()
        collectionView.reloadData()
    }

这里是 CollectionViewDataSource 方法:

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
   return gifts.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

   let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! GiftCollectionViewCell
   cell.gift = gifts[indexPath.item]
   return cell

}

最佳答案

当你想刷新 collectionView 中的数据时,你必须在主线程中重新加载数据。

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

关于swift - 无法将项目附加到 CollectionView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36788872/

相关文章:

ios - 如何通过在SwiftUI中触摸屏幕的任何位置来更改文本

ios - CollectionView中的程序化搜索栏实现问题

ios - 如何通过按钮播放服务器中的视频

ios - 是否可以在 collectionview sizeForItemAtIndexPath 委托(delegate)方法中获取单元格的标签?

arrays - fatal error : Array index out of range.关于collectionView

ios - 依次执行一段代码

ios - 在其他屏幕中更新绑定(bind)后,SwiftUI 列表行未刷新

ember.js - 如何将模板与 Ember.CollectionView 一起使用

iOS Swift UICollectionView registerNib 可重用 View 不起作用

ios - 无法从 PFQueryCollectionViewController Swift iOS 中的 Parse 加载数据