我正在嘗試使用UICollectionView
來顯示在UIImageView
中具有動畫GIF的正方形MyCollectionViewCell
。Swift UICollectionViewCell當滾動時隨機空白的動畫視圖
行和段都設置像這樣:
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 50
}
我使用SwiftGif獲得分配給該小區的UIImageView
像這樣的GIF:
let gifs = [UIImage.gifWithName("gif1"), UIImage.gifWithName("gif2"), UIImage.gifWithName("gif3")]
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("gifCell", forIndexPath: indexPath) as! GifCollectionViewCell
cell.gifImageView.image = gifs[indexPath.item % gifs.count]
return cell
}
一切大部分的偉大工程。但我的問題是,當滾動時,有時單元格是空白的,沒有GIF出現。在調試過程中,我在單元格中添加了一個標籤以顯示indexPath.item
,如您在上面的代碼中看到的,以確保單元格不會被傳遞,並且發現標籤將始終顯示indexPath如果單元格不顯示GIF。
我已經與普通圖像測試,而不是像這樣:
let testImages = [UIImage(named: "testImage1"), UIImage(named: "testImage2", UIImage(named: "testImage3")]
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("gifCell", forIndexPath: indexPath) as! GifCollectionViewCell
cell.gifImageView.image = testImages[indexPath.item % testImages.count]
return cell
}
,並沒有出現空白單元格中。
更加好奇了,當我最初實際生成GIF在collectionView(...cellForItemAtIndexPath)
我沒有得到任何問題空白單元之一:
let gifNames = ["gif1", "gif2", "gif3"]
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("gifCell", forIndexPath: indexPath) as! GifCollectionViewCell
let gif = UIImage.gifWithName(gifNames[indexPath.item % gifNames.count])
cell.gifImageView.image = gif
return cell
}
,如果它是不是事實這種原始的實現會工作的GIF構建過程極大地影響了UICollectionView
的滾動性能,這迫使我首先改變實現。
我已經確認這是不是SwiftGif一個問題,因爲我已經在不同的應用中使用動畫渲染庫複製這個問題,並在地方UIImageView
的MyCollectionViewCell
的AnimatedView
並顯示動畫,而不是GIF格式,得到了相同在滾動CollectionView時,單元格會隨機顯示任何內容而不是動畫。
我曾嘗試StackOverflow的解決方案here並實現了自定義UICollectionViewFlowLayout
像這樣:
class MyFlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attributes = super.layoutAttributesForElementsInRect(rect)
let contentSize = self.collectionViewContentSize()
let newAttrs = attributes?.filter { $0.frame.maxX <= contentSize.width && $0.frame.maxY <= contentSize.height}
return newAttrs
}
}
並賦予它在viewDidLoad()
像這樣:
self.collectionView?.collectionViewLayout = MyFlowLayout()
在MyFlowLayout
我也曾嘗試:
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
我也混淆了各種單元格大小(寬度1小於高度,高度1小於寬度等),並與某些部分插入組合混亂,但沒有設法找到導致動畫視圖的問題的來源現身。
任何幫助,將不勝感激。謝謝