ios - cellForItem(位于 : IndexPath) method doesn't call with UICollectionViewCell subclass

标签 ios swift uicollectionview uicollectionviewcell

在 Xcode 中,我在 userCell 中创建了一个 var“userImage” - UICollectionViewCell 的子类。

import UIKit

class userCell: UICollectionViewCell {

    @IBOutlet weak var userImage: UIImageView!
}

现在我想在我的 Collection View 上实现 cellForItem(at: IndexPath) 方法,但它返回的单元格没有“userImage”变量。

代码如下:

self.collection.cellForItem(at: path).userImage.image = UIImage(named: "1.jpg")

给出错误“‘UICollectionViewCell’类型的值?”没有成员“userImage””

代码如下:

self.collection.cellForItem(at: path) as userCell.userImage.image = UIImage(named: "1.jpg")

给出错误“Var 'userImage'不是'userCell'的成员类型”

最佳答案

您的代码推断 UICollectionViewCell 没有具有该名称的属性,因此您必须将其显式转换为 userCell,并使用 ? 作为该单元格可能为零以避免崩溃

 let cell = self.collection.cellForItem(at: path) as? userCell

 cell?.userImage.image = UIImage(named: "1.jpg")

还要确保 userImage 正确连接到单元格 Xib 中的 imageView

关于ios - cellForItem(位于 : IndexPath) method doesn't call with UICollectionViewCell subclass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48132330/

相关文章:

ios - 如何正确地使 UICollectionView 中补充 View 的布局无效

ios - Facebook Graph API 更改了今天的结果/帖子?

iphone - 需要 AVFoundation 缩放帮助

ios - Facebook sdk 集成打开移动站点登录屏幕而不是在 IOS 中询问权限

iphone - 如何获取捕获视频的缩略图并显示在 UIImageView 中

ios - SwiftUI 无法添加 onChange 事件

ios - 在 XCode 6 beta 7 中从 Swift 在 iOS 中打印

swift - 如何限制自定义 UIControl 旋钮的运动范围?

swift - 如何在 Swift 的 UICollectionViewCell 中将图像显示到中心

ios - UICollectionView 滚动整个页面