ios - Swift3 - 带有图像的单元格不显示

标签 ios swift3 uiimageview uicollectionview uicollectionviewcell

我尝试将背景 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/

相关文章:

ios - 从 Swift 函数中的异步调用返回数据

ios - 如何创建一个通用函数来加载 View Controller ?

swift - 试图在 UIImageView 上放置徽章

swift - 了解 crashlytics UIKit 错误

ios - 如何在 iOS Swift 中实现标签嵌入到 UIImageView 中,如图所示?

ios - 将 UIImageView 添加到 UIScrollView

ios - 在初始化时隐藏 UILabel

ios - xcode 控制台中的 GKSConnSettings 消息

objective-c - UIApplication _preferredInterfaceOrientationGivenCurrentOrientation : SIGABRT

swift - SiriKit Intents UI - Payment Domain - Center Area 重复三次