2017-02-28 84 views
0

我試圖訪問單元格單擊時連接到UICollectionView單元格中的所有子視圖。獲取單元格onClick在UICollectionView中的所有子視圖swift

我能夠添加圖像和標籤給它,但它顯示爲零時,我對任何細胞

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) 

    // Image  
    let imageview:UIImageView = UIImageView(frame: CGRect(x: 5, y: 5, width: myCell.frame.width - 10, height: myCell.frame.height - 20)) 
    imageview.image = UIImage(named: String(format: "%@.png", arr[indexPath.row])) 
    imageview.tag = 20 

    // Label 
    let label = UILabel(frame: CGRect(x: 5, y: 50, width: myCell.frame.width - 10, height: myCell.frame.height - 40)) 
    label.textAlignment = .center 
    label.text = arr[indexPath.row] 
    label.textColor = .black 
    label.tag = 21 
    label.font = label.font.withSize(8) 

    myCell.contentView.addSubview(imageview) 
    myCell.contentView.addSubview(label) 

    myCell.backgroundColor = UIColor.white 

    return myCell 
} 

挖掘,我試圖訪問下面的子視圖:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
    let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) 
    print(myCell.contentView.subViews) // Returns null 
} 

我知道我們可以使用indexPath.row獲得物品索引。但我想讀取子視圖。如何得到它?感謝您的幫助

+1

您需要使用'cellForItem(在:)'來獲得細胞,所以它應該是'讓電池= collectionView.cellForItem(在:indexPath)' –

+0

@NiravD,是的,它現在的工作。謝謝:) – SunShine

+0

如果你使用'cellForItem(at:)'獲得'subViews' nil''就像'let cell = collectionView.cellForItem(at:indexPath);打印(cell.contentView.subviews)' –

回答

3
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
    let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) 
    print(myCell.contentView.subViews) // Returns always null 
} 

UICollectionView的方法dequeueReusableCell返回一個新的可重複使用的電池,現在myCell有新的基準,並始終成爲新的參考,如果你想獲得舊的細胞,你需要從

let cell = collectionView.cellForItemAtIndexPath(indexPath) as! MyCell 

獲得細胞,如果你有類使用MyCell其他您可以直接獲取單元格而無需進行類型轉換

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
    let cell = collectionView.cellForItemAtIndexPath(indexPath) 
    print(cell.contentView.subviews) 
} 
0

試試這個代碼是didSelectMethod

let cell = collectionView.cellForRowAtIndexPath(indexPath) as! MyCollectionViewCell 
print(cell) 
相關問題