2014-11-01 118 views
1

在我的項目的價值存在的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!) 
     } 
    } 
} 

如果你能解釋如何設置一個值和如何在這種情況下返回,我會很感激!

並請幫我找出什麼地方錯了展開的價值,誰是零?

感謝您提前給予任何幫助!

回答

1

的問題是,你檢索與您的通話dequeueReusableCell...未配置的電池。相反,您需要致電cellForItemAtIndexPath

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

哦,我的上帝!好像我忘了我的眼睛!非常感謝! :) – Majotron 2014-11-01 14:55:22