【问题标题】:cellForItem(at: IndexPath) method doesn't call with UICollectionViewCell subclasscellForItem(at: IndexPath) 方法不使用 UICollectionViewCell 子类调用
【发布时间】:2018-01-06 21:59:27
【问题描述】:

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

import UIKit

class userCell: UICollectionViewCell {

    @IBOutlet weak var userImage: UIImageView!
}

现在我想在我的集合视图上实现 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' 的成员类型”

【问题讨论】:

    标签: ios swift uicollectionview uicollectionviewcell


    【解决方案1】:

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

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

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

    【讨论】:

    • 另外,类名应该以大写开头,所以正确的名称是“UserCell”。使用“userCell”表明它是类的实例。
    • 我已经完成了,但是 swift 抱怨 userImage 是可选的,带有感叹号的应用程序崩溃,因为 userImage 的值为 nil,带有问号则没有任何反应
    • 首先检查该单元格是否为 nil,因为它可能当前未显示
    • 让 foto = UIImage(data: data!) if let cc = self.collection.cellForItem(at: path) as? UserCell{ if let userimage = cc.userImage { userimage.image = foto }else{ print("userimage is nil") } }else{print("cell is nil")} 在控制台打印“userimage is nil”
    • userimage 可能没有连接到 xib 中的 imageView
    猜你喜欢
    • 2019-04-11
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多