我试图将背景视图设置为图像,但它从不显示带有图像的单元格。我可以向下滚动,所以我知道那里确实有单元格,但是没有背景图像,每当我滚动得非常快,你就可以找到正确的图像,但它会很快消失。
任何想法为什么?
继承我的代码:
let image: UIImageView = {
let imgview = UIImageView()
imgview.image = UIImage(named: "myImage")
imgview.contentMode = .scaleAspectFit
imgview.clipsToBounds = true
return imgview
}()
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell-id", for: indexPath)
cell.contentView.addSubview(image)
cell.backgroundView = image
return cell
}
答案 0 :(得分:1)
您不应在addSubview
中调用cellForItemAt
方法。因为cellForItemAt
被多次调用。
试试这段代码:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell-id", for: indexPath)
UIGraphicsBeginImageContext(cell.frame.size)
UIImage(named: "myImage")?.draw(in: cell.bounds)
if let image: UIImage = UIGraphicsGetImageFromCurrentImageContext() {
UIGraphicsEndImageContext()
cell.backgroundColor = UIColor(patternImage: image)
}
return cell
}