无法访问属性
问题描述:
在我的项目的价值存在的UICollectionViewCell
一个子类。自定义单元格有一个标签的属性。在初始化一个UICollectionView
实例时,我也注册了自定义单元类及其标识符。问题在于该属性是可选的,因此理论上它可以是零。我在配置单元格时设置了属性,它不应该是零。同时展开一个可选值成立为零 - 即使它与UILabel
现有实例分配我有一个运行时错误。无法访问属性
我用我的手机代码:
class MonthCalendarCell: UICollectionViewCell {
var dateLabel: UILabel?
func addDateLabel(label: UILabel) {
self.dateLabel = label
self.addSubview(label)
}
}
这是一个集合视图的初始化:
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 /访问和初始化的设置方式,但它不能很好地工作。
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!)
}
哦,我的上帝!好像我忘了我的眼睛!非常感谢! :) – Majotron 2014-11-01 14:55:22