Swift3 - 不显示带有图像的单元格
Swift3 - Cells with image is not displayed
我试图将背景视图设置为图像,但它从不显示带有图像的单元格。我可以向下滚动,所以我知道那里确实有单元格,但没有背景图像,每当我滚动得非常快时,你可以辨认出正确的图像,但它很快就消失了。
知道为什么吗?
这是我的代码:
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
}
我试图将背景视图设置为图像,但它从不显示带有图像的单元格。我可以向下滚动,所以我知道那里确实有单元格,但没有背景图像,每当我滚动得非常快时,你可以辨认出正确的图像,但它很快就消失了。
知道为什么吗?
这是我的代码:
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
}