在 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/