0
我正在使用Pinterest式2列布局实现应用程序。并希望每个单元格的大小都是动态的,与图像的大小相对应。UICollectionView异步更新大小
我使用SDWebImage将图像异步加载到单元格,然后使collectionView的布局无效。但是由于单元格是可重用的,因此每次屏幕向下滚动时,布局将失效并产生一些不需要的动画。
这里是我的代码:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCellWithReuseIdentifier(self.identifier, forIndexPath: indexPath) as! MyCell
cell.imageView.sd_setImageWithURL(imageUrl, completed: { (image, error, _, _) -> Void in
UIView.animateWithDuration(0.3, animations: {() -> Void in
collectionView.collectionViewLayout.invalidateLayout()
})
})
return cell
}
细胞大小功能:
func collectionView(collectionView: UICollectionView!, layout collectionViewLayout: UICollectionViewLayout!, sizeForItemAtIndexPath indexPath: NSIndexPath!) -> CGSize {
var width = UIScreen.mainScreen().bounds.size.width/2 - 3
// create a cell size from the image size, and return the size
if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CraveCollectionViewCell{
if cell.imageView.image != nil {
let image = cell.imageView.image!
var height = image.size.height * width/image.size.width
let size = CGSize(width: width, height: height)
var height1 = size.height > 160 ? size.height : 160
return CGSize(width: width, height: height1)
}
}
return CGSize(width: width, height: 160)
}
}
当图像被SDWebImage首先得到负荷,collectionView.collectionViewLayout.invalidateLayout()
被称为和布局工作正常。
经过大幅调整后,collectionView.collectionViewLayout.invalidateLayout()
被再次调用,问题出现在这里。
你添加了这个动画:animateWithDuration,你可以不用动画和检查 – Swati
@Swati谢谢你的评论。在滚动期间,每次布局仍然失效,仍然可以看到一些干扰正在进行。我想找到一种方法来摆脱它。 – Zeyu