【发布时间】:2015-02-28 19:46:17
【问题描述】:
我正在学习 Swift,并且正在编写一个小应用程序来显示带有图像的集合视图。它不起作用,并且图像永远不会显示。我在collectionView cellForItemAtIndexPath 中看到了奇怪的行为:当我延迟加载要在单元格中显示的图像并第二次调用collectionView.dequeueReusableCellWithReuseIdentifier() 时,它返回一个不同的单元格。这发生在我滚动集合视图之前,因此单元格重用应该不是问题。这是我的代码:
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let reuseIdentifier = "CollectionCell"
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath:indexPath) as! ImageCollectionCell
cell.imageView.contentMode = UIViewContentMode.ScaleAspectFill
cell.countLabel.text = "\(indexPath.row+1)"
let imageIndex = XKCDClient.sharedInstance.totalCount - indexPath.row - 1
println("loading image # \(imageIndex)")
XKCDClient.sharedInstance.loadComic(imageIndex, completion: { (comicData) -> Void in
if let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath:indexPath) as? ImageCollectionCell {
println("got image # \(imageIndex)")
cell.imageView.backgroundColor = UIColor.blackColor()
if(comicData.image != nil) {
// cell.imageView.image = comicData.image // (1)
cell.imageView.image = UIImage(named: "placeholder") // (2)
cell.setNeedsDisplay()
}
}
else {
println("cell \(imageIndex) already reused");
}
})
return cell
}
会发生什么:
- 为每个索引路径调用回调块
-
UIImage对象已正确传递到回调块中 - 对回调中的单元格没有任何更改似乎有任何效果(包括设置背景颜色)
- 回调中
collectionView.dequeueReusableCellWithReuseIdentifier()返回的单元格与方法开头返回的单元格不同。这似乎是问题的根源。
谁能解释一下这里发生了什么?
【问题讨论】:
标签: ios swift uiimageview uicollectionview lazy-loading