简体   繁体   English

UICollectionViewCell中没有出现多个按钮

[英]Multiple Buttons not appearing in UICollectionViewCell

I am attempting to programmatically create a button in each cell of a UICollectionView; 我试图以编程方式在UICollectionView的每个单元格中创建一个按钮; however, only the first button is visible. 但是,只有第一个按钮可见。 I have tried adding print statements to see what subviews my cells have and the button is present but it is not appearing on the screen. 我尝试添加打印语句,以查看单元格具有哪些子视图,并且该按钮存在,但该按钮未出现在屏幕上。

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
}

Also, I added a print statement when clicking the buttons and only the first button shows up and prints out 0. 另外,我在单击按钮时添加了一条打印语句,只有第一个按钮显示并打印出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 这是收藏夹视图的屏幕快照,图片中应该有两个按钮,但只有一个出现

Any help is much appreciated. 任何帮助深表感谢。

It's very bad to add button in data source, because when cell reused, new buttons will be created. 在数据源中添加按钮非常不好,因为当单元重用时,将创建新的按钮。 If you're using Interface Builder, please add button directly. 如果您使用的是Interface Builder,请直接添加按钮。 And you can adjust their properties. 您可以调整它们的属性。 You can also define a custom cell, and just CTRL-Drag an outlet. 您还可以定义一个自定义单元格,只需按住CTRL键并拖动一个插座即可。 Or handle selection in collection view's delegate. 或在集合视图的委托中处理选择。

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

Another solution is add button in cell's awakeFromNib() , this will be called only once. 另一种解决方案是在单元格的awakeFromNib()添加按钮,此按钮仅被调用一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM