多个按钮未出现在 UICollectionViewCell 中

Multiple Buttons not appearing in UICollectionViewCell

我正在尝试以编程方式在 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

非常感谢任何帮助。

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

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

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