【问题标题】:Multiple Buttons not appearing in UICollectionViewCellUICollectionViewCell 中没有出现多个按钮
【发布时间】:2017-12-14 22:15:25
【问题描述】:

我正在尝试以编程方式在 UICollectionView 的每个单元格中创建一个按钮;但是,只有第一个按钮可见。我尝试添加打印语句以查看我的单元格有哪些子视图,并且按钮存在但它没有出现在屏幕上。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath)
    // Configure the cell

    let button = UIButton(frame: cell.frame)
    button.addTarget(self, action: #selector(cellClicked), for: UIControlEvents.touchUpInside)
    button.backgroundColor = UIColor.red
    button.tag = indexPath.row
    cell.addSubview(button)

    print(cell.subviews)

    return cell
}

另外,我在点击按钮时添加了一个打印语句,只有第一个按钮显示并打印出 0。

@IBAction func cellClicked(sender: UIButton) {
    print(sender.tag)
}

Here is a screenshot of the collection view, there should be two buttons in the picture but only one appears

非常感谢任何帮助。

【问题讨论】:

  • collectionView 数据源中有多少条数据记录?
  • 我当前的测试用例中有两条数据记录

标签: ios swift uibutton uicollectionview uicollectionviewcell


【解决方案1】:

在数据源中添加按钮是非常糟糕的,因为当重复使用单元格时,会创建新的按钮。如果您使用的是 Interface Builder,请直接添加按钮。您可以调整它们的属性。您还可以定义一个自定义单元格,然后按住 CTRL 并拖动一个插座。或者在集合视图的委托中处理选择。

optional public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)

另一种解决方案是在单元格的awakeFromNib() 中添加按钮,这只会被调用一次。

【讨论】:

  • 我按照您的建议在单元格的 awakeFormNib() 中添加了代码并且它有效。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-07
  • 2014-08-20
  • 1970-01-01
  • 1970-01-01
  • 2017-08-05
  • 2014-01-19
相关资源
最近更新 更多