我試圖訪問單元格單擊時連接到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)' –