我尝试将背景 View 设置为图像,但它从不显示带有图像的单元格。我可以向下滚动,这样我就知道那里确实有单元格,但没有背景图像,每当我滚动得非常快时,您就可以辨认出正确的图像,但它很快就会消失。
有什么想法吗?
这是我的代码:
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
}
最佳答案
您不应该在 cellForItemAt
中调用 addSubview
方法。因为 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
}
关于ios - Swift3 - 带有图像的单元格不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45537762/