UICollectionView的奇怪行为

时间:2016-12-14 12:05:11

标签: ios objective-c swift uicollectionview

正如您在附加的GIF中看到的那样,UICollectionView工作正常,但单元格中的图像不稳定(首先您看到一个图像,然后图像变为右图像。)

GIF示例: http://d.pr/i/ZccO

刷新触发器:

self?.productsCollectionView.reloadData()

创建每个单元格的collectionView函数:

    // make a cell for each cell index path
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    // Check if need to load more battles
    if indexPath.item + Constants.bufferToLoad >= (Constants.pageSize * self.page) && Constants.pageSize * self.page < self.totalProducts {
        self.page += 1
        self.getProducts(false)
    }
    var cell:UICollectionViewCell?
    if self.isLoading && indexPath.item == self.products.count-1 {
        cell = collectionView.dequeueReusableCellWithReuseIdentifier(Constants.loadigCell, forIndexPath: indexPath) as? LoadingCollectionViewCell
        (cell as! LoadingCollectionViewCell).activityView.startAnimating()
    } else {
        cell = collectionView.dequeueReusableCellWithReuseIdentifier(Constants.cellName, forIndexPath: indexPath) as? SavedProductCollectionViewCell
        let productCell = cell as! SavedProductCollectionViewCell
        productCell.product = self.products[indexPath.item]
    }

    return cell!
}

这是我为每个CollectionViewCell设置图像的方法:

    var product:Product! {
    didSet {
        self.updateUI()
    }
}
override func awakeFromNib() {
    super.awakeFromNib()
    self.layer.cornerRadius = 5
    self.layer.masksToBounds = true
}

func updateUI() {
    self.productImage.loadImageFromURLString(self.product.mainImage!,placeholderImage: UIImage(named: "placeHolder"))
    self.productNameLabel.text = self.product?.name
    self.productPriceLabel.text = self.product?.price
    self.setPicks()
}

1 个答案:

答案 0 :(得分:0)

细胞被重复使用。当返回重用的单元格时,它仍将包含旧图像,直到新图像的加载完成为止。您应该将图片设置为nilcellForItemAtIndexLath或单元格prepareForReuse方法中的某个占位符图片。

override func prepareForReuse() {
   self.productImage = nil
   self.productNameLabel.text = ""
   self.productPriceLabel.text = ""
}
相关问题