0

我有一個UICollectionView,並且在每個單元中予設定的UILabel的文本中,在cellForItemAtIndexPath,從數組:UICollectionView委託方法沒有被調用正確

let array = ["New York City", "Chicago", "San Francisco"] 

細胞出現標記的正確屏幕上,但是當我嘗試在didSelectItemAtIndexPath中記錄標籤的值,它將該值記錄爲nil。如果我嘗試在didSelectItemAtIndexPath中執行其他任何操作(例如更改單元格的不透明度),則不會執行任何更改。

這裏可能會出現什麼問題?


相關的代碼:

視圖控制器具有超UICollectionViewDataSourceUICollectionViewDelegateFlowLayout

集合觀察室的類聲明:

class PickerCell: UICollectionViewCell { 
var label = UILabel() 

override init(frame: CGRect) { 
    super.init(frame: frame) 
    contentView.backgroundColor = UIColor.clearColor() 

    label.frame = contentView.bounds 
    label.textColor = UIColor.whiteColor() 
    label.textAlignment = NSTextAlignment.Left 
    label.font = font.body 
    contentView.addSubview(label) 
} 

required init?(coder aDecoder: NSCoder) { 
    super.init(coder: aDecoder) 
} 
} 

創建集合視圖:

func createPickerView() { 
    let pickerFlowLayout: UICollectionViewFlowLayout = PickerLocationFlowLayout() 
    pickerFlowLayout.itemSize = CGSize(width: screenSize.width, height: 40) 
    pickerFlowLayout.minimumLineSpacing = 0 

    let pickerView: UICollectionView 
    pickerView = UICollectionView(frame: CGRectMake(0, 0, screenSize.width, screenSize.height), collectionViewLayout: pickerFlowLayout) 
    pickerView.registerClass(PickerCell.self, forCellWithReuseIdentifier: "PickerCellId") 
    pickerView.delegate = self 
    pickerView.dataSource = self 
    self.view.addSubview(pickerView) 
} 

選擇單元格:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PickerCellId", forIndexPath: indexPath) as! PickerCell 
    print("indexpath: \(indexPath.row), label: \(cell.label.text)") 
    // Prints the correct row number, but nil for the label. 
} 
+0

您是否添加了collectionView.delegate和.dataSource = self? – Lee

+0

是的,如'createPickerView()'所示,委託和數據源確實設置爲'self'。 –

回答

0

原來我犯了一個愚蠢的錯誤。在didSelectItemAtIndexPath,我打電話dequeueReusableCellWithReuseIdentifier,我應該叫cellForItemAtIndexPath