我使用 Alamofire 库在 collectionView 的单元格中显示图像 但我的问题是当我向上 && 向下滚动时,我的 CollectionView 在单元格中显示错误的图像
这是我设置单元格数据的代码片段
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CardViewCell
let pos = indexPath.item % 5
var paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 2.5
paragraphStyle.alignment = .Right
paragraphStyle.lineBreakMode = .ByTruncatingTail
if let text = currentCollection.titles?[indexPath.item] {
var attrString = NSMutableAttributedString(string: text)
attrString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range:NSMakeRange(0, attrString.length))
cell.title.attributedText = attrString
} else {
cell.title.text = currentCollection.titles?[indexPath.item]
}
if let catId = currentCollection.catIds?[indexPath.item] {
cell.iconImage.image = UIImage(named: icons[catId-1])
}
cell.title.font = UIFont(name: "B Yekan", size: 14)
cell.title.preferredMaxLayoutWidth = cell.frame.size.width - 48
cell.iconImage.image = cell.iconImage.image!.imageWithRenderingMode(.AlwaysTemplate)
cell.iconImage.tintColor = UIColor.whiteColor()
let imageUrl = currentCollection.urlImages![indexPath.item]
if let image = currentCollection.imageCache.objectForKey(imageUrl) as? UIImage {
cell.backImage.image = image
} else {
cell.backImage.image = nil
cell.request = Alamofire.request(.GET, imageUrl).validate(contentType: ["image/*"]).responseImage() {
(request, _, image, error) in
if error == nil && image != nil {
self.currentCollection.imageCache.setObject(image!, forKey: request.URLString)
cell.backImage.image = image
}
}
}
cell.layer.shadowPath = UIBezierPath(roundedRect: cell.bounds, cornerRadius: cell.layer.cornerRadius).CGPath
if indexPath.item == currentCollection.titles!.count-3 {
currentCollection.page++
appendTitlesInPage(currentCollection.page)
}
return cell
}
能帮我看看哪里错了吗?请!
最佳答案
图像请求需要时间 - 在此期间,请求保持对单元格的引用,并在请求完成后设置单元格的 backImage.image
。不幸的是,到那时,该单元格可能已经滚动到屏幕外,并且可能在图像不正确的另一个 indexPath 处重新使用。相反,您应该使用 TableView 的 cellForItemAtIndexPath
方法来获取正确的单元格(如果单元格不再可见,这将返回 nil 以防止您出错)。
关于ios - 在 ios 中使用 Alamofire 在 collectionView 中显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30534544/