无法访问属性的值

时间:2014-11-01 14:06:56

标签: ios swift uicollectionview

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

我用于我的手机的代码:

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 / set方式访问和初始化,但它不能正常工作。

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

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

如果您能解释如何设置值以及如何返回,我会感激不尽!

请帮我弄清楚打开价值有什么问题,谁是零呢?

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

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

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