gpt4 book ai didi

ios - 无法访问属性的值

转载 作者:行者123 更新时间:2023-11-28 07:15:02 24 4
gpt4 key购买 nike

在我的项目中有一个 UICollectionViewCell 的子类。自定义单元格具有标签属性。在初始化 UICollectionView 实例时,我还使用其标识符注册了自定义单元格类。问题在于该属性是可选的,因此理论上它可以为零。我在配置单元格时设置了属性,它不应该为零。尽管它已分配有 UILabel 的现有实例,但我遇到了运行时错误 - 在展开可选值时发现 nil

我用于手机的代码:

class MonthCalendarCell: UICollectionViewCell {
var dateLabel: UILabel?

func addDateLabel(label: UILabel) {
self.dateLabel = label
self.addSubview(label)
}
}

这是 Collection View 的初始化:

override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
let calendarFlowLayout = CalendarFlowLayout()

super.init(frame: frame, collectionViewLayout: calendarFlowLayout)

self.dataSource = self
self.delegate = self
self.registerClass(MonthCalendarCell.self, forCellWithReuseIdentifier: self.identifier)

// TODO: work on this
self.backgroundColor = UIColor.groupTableViewBackgroundColor()
}

配置单元格:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(self.identifier, forIndexPath: indexPath) as MonthCalendarCell

let label = UILabel()
label.text = "1"
label.frame = CGRectMake(0, 0, cell.bounds.width, cell.bounds.height)
label.textAlignment = NSTextAlignment.Center
label.backgroundColor = UIColor.redColor()

self.highlightView(label)

cell.addDateLabel(label)

return cell
}

问题出现在这里:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(self.identifier, forIndexPath: indexPath) as MonthCalendarCell
println(cell.dateLabel!)
}

我也尝试过使用get/set方式访问和初始化,但效果不佳。

class MonthCalendarCell: UICollectionViewCell {
var dateLabel: UILabel? {
get {
return self.dateLabel
}

set(label) {
self.addSubview(label!)
}
}
}

如果您能解释如何设置值以及在这种情况下如何返回,我将不胜感激!

请帮我弄清楚解包值有什么问题,它是谁的零?

提前感谢您的帮助!

最佳答案

问题是您正在使用 dequeueReusableCell... 调用检索未配置的单元格。相反,您需要调用 cellForItemAtIndexPath:

if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? MonthCalendarCell {
println(cell.dateLabel!)
}

关于ios - 无法访问属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26690045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com