【问题标题】:get all the subviews of a cell onClick in UICollectionView swift在 UICollectionView swift 中获取单元格 onClick 的所有子视图
【发布时间】: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


【解决方案1】:
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)
}

【讨论】:

    【解决方案2】:

    试试这个代码是didSelectMethod

    let cell = collectionView.cellForRowAtIndexPath(indexPath) as! MyCollectionViewCell
    print(cell)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      • 1970-01-01
      • 2019-10-20
      • 2013-02-24
      • 1970-01-01
      相关资源
      最近更新 更多