我试图访问单元格单击时连接到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
获得物品索引。但我想读取子视图。如何得到它?感谢您的帮助
您需要使用'cellForItem(在:)'来获得细胞,所以它应该是'让电池= collectionView.cellForItem(在:indexPath)' –
@NiravD,是的,它现在的工作。谢谢:) – SunShine
如果你使用'cellForItem(at:)'获得'subViews' nil''就像'let cell = collectionView.cellForItem(at:indexPath);打印(cell.contentView.subviews)' –