2017-07-11 15 views
0

我試圖以編程方式在UICollectionView的每個單元中創建一個按鈕;但是,只有第一個按鈕是可見的。我曾嘗試添加打印語句以查看我的單元格具有哪些子視圖,並且該按鈕存在但未顯示在屏幕上。未顯示在UICollectionViewCell中的多個按鈕

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) 
    // Configure the cell 

    let button = UIButton(frame: cell.frame) 
    button.addTarget(self, action: #selector(cellClicked), for: UIControlEvents.touchUpInside) 
    button.backgroundColor = UIColor.red 
    button.tag = indexPath.row 
    cell.addSubview(button) 

    print(cell.subviews) 

    return cell 
} 

另外,我點擊按鈕,只有第一個按鈕顯示並打印出來時0

@IBAction func cellClicked(sender: UIButton) { 
    print(sender.tag) 
} 

Here is a screenshot of the collection view, there should be two buttons in the picture but only one appears

任何幫助是非常讚賞加一個print語句。

+0

您在'collectionView'數據源中有多少條數據記錄? – Lawliet

+0

我在我當前的測試用例中有兩個數據記錄 – Armand

回答

0

在數據源中添加按鈕非常不好,因爲當單元格被重用時,將會創建新的按鈕。如果您使用Interface Builder,請直接添加按鈕。你可以調整它們的屬性。您也可以定義一個自定義單元格,並只需CTRL-拖動一個插座。或者在集合視圖的委託中處理選擇。

optional public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) 

另一種解決方案是增加細胞的awakeFromNib()按鈕,這將是一次調用。

+0

我像你所建議的那樣在單元的awakeFormNib()中添加了代碼,它工作正常。謝謝! – Armand