单击单元格时,我尝试访问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
获取项目索引。但我想阅读子视图。怎么弄?谢谢你的帮助
答案 0 :(得分: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)
}
答案 1 :(得分:0)
尝试此代码为didSelectMethod
let cell = collectionView.cellForRowAtIndexPath(indexPath) as! MyCollectionViewCell
print(cell)