【问题标题】:Swift3 - Cells with image is not displayedSwift3 - 不显示带有图像的单元格
【发布时间】:2018-01-14 05:16:34
【问题描述】:

我试图将背景视图设置为图像,但它从不显示带有图像的单元格。我可以向下滚动,所以我知道那里确实有单元格,但没有背景图像,每当我快速滚动时,您可以找出正确的图像,但它很快就会消失。

有什么想法吗?

这是我的代码:

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
}

【问题讨论】:

    标签: ios swift3 uiimageview uicollectionview uicollectionviewcell


    【解决方案1】:

    你不应该在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
    }
    

    【讨论】:

    • 这段代码也对我有用!我现在将它用于 UITableView 中的单元格。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多