2017-02-28 81 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) 
相关问题