如何在集合视图单元格中添加 uibutton 操作?

How to add uibutton action in a collection view cell?

所以我有这个集合视图,其中的单元格包含一个编辑按钮,位于右上角。我如何将动作连接到其中?

我尝试在 collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 中添加 cell.editbutton.addTarget 但它没有检测到 touchUpInside 事件。

可能对你有帮助-

将这段代码写在cellForItemAtIndexPath

Swift 2.X

let editButton = UIButton(frame: CGRectMake(0, 20, 40,40))
editButton.setImage(UIImage(named: "editButton.png"), forState: UIControlState.Normal)
editButton.addTarget(self, action: #selector(editButtonTapped), forControlEvents: UIControlEvents.TouchUpInside)

cell.addSubview(editButton)

Swift 3.X

let editButton = UIButton(frame: CGRect(x:0, y:20, width:40,height:40))
editButton.setImage(UIImage(named: "editButton.png"), for: UIControlState.normal)
editButton.addTarget(self, action: #selector(editButtonTapped), for: UIControlEvents.touchUpInside)

cell.addSubview(editButton)

并执行你的操作-

override func viewDidLoad() {
       super.viewDidLoad()
}

@IBAction func editButtonTapped() -> Void {
    print("Hello Edit Button")
}

在 UICollectionViewCell 中创建 UIButton 的 outlet,写在

func collectionView(_ collectionView: UICollectionView, 
                    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    cell.button.tag = indexPath.row
    cell.button.addTarget(self, 
        action: #selector(self.yourFunc(), 
        for: .touchUpInside)
}

func yourFunc(sender : UIButton){
    print(sender.tag)
}

确保为按钮和 UICollectionViewCell 启用了 userInteraction。

在 UICollectionView 单元格上获取按钮(以编程方式或使用故事板)。在单元格 class 文件中为该按钮添加操作,并在该单元格 class 文件中声明委托,并在按钮操作方法中调用相同的委托来执行编辑操作。

然后在您创建集合视图的 ViewController 中实现相同的委托

protocol CollectionViewCellDelegte {
    func collectionViewCellDelegte(didClickButtonAt index: Int)
}

class ImageCollectionViewCell: UICollectionViewCell {
    var index = 0
    var delegte: CollectionViewCellDelegte? = nil

    @IBAction func buttonAction(_ sender: UIButton) {
        if let del = self.delegte {
            del.collectionViewCellDelegte(didClickButtonAt: index)
        }
    }
}

据我所知,您想调用编辑按钮操作而不是 didSelectItemAt:indexPath。 我通过重写 canBecomeFocused(return false)解决了这个问题,然后您的编辑按钮操作将通过点击编辑按钮

参与