【发布时间】:2017-02-28 12:11:47
【问题描述】:
单击单元格时,我正在尝试访问附加到UICollectionView 中的单元格的所有子视图。
我可以添加图像和标签,但是当我点击任何单元格时它显示为零
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 获取项目索引。但我想阅读子视图。如何得到它?感谢您的帮助
【问题讨论】:
-
获取cell需要使用
cellForItem(at:),所以应该是let cell = collectionView.cellForItem(at: indexPath) -
@NiravD,是的,它现在工作了。谢谢你:)
-
标签: ios iphone swift uicollectionview