ios - 在 UICollectionView swift 中获取单元格 onClick 的所有 subview

标签 ios iphone swift uicollectionview

我试图在单击单元格时访问附加到 UICollectionView 中单元格的所有 subview 。

我可以给它添加图像和标签,但是当我点击任何单元格时它显示为 nil

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
}

我正在尝试访问如下 subview :

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath)
  print(myCell.contentView.subViews) // Returns null
}

我知道我们可以使用 indexPath.row 获取项目索引。但我想阅读 subview 。如何得到它?感谢您的帮助

最佳答案

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)
}

关于ios - 在 UICollectionView swift 中获取单元格 onClick 的所有 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42508463/

相关文章:

ios - 适用于企业内部APP的iOS推送通知

ios - 动画 UISearchBar 框架的宽度

IOS 电脑键盘输入

iphone - 知道歌曲何时播放完毕

ios - 无法将 CollectionViewCell 移动到末尾

iphone - mc_mobile_tunnel 在崩溃日志中代表什么?

iphone - ios 对象在 Debug 模式下会被释放,但在 Release 模式下不会被释放

iphone - 如何更改 UIImagePicker ViewController 中的“选择”按钮标题?

IOS(Swift 3)打开/关闭gps时如何触发广播接收器?

ios - SKLabelNode 不尊重 zPosition?