首页 > 解决方案 > collectionViewCell 中的按钮不触发功能

问题描述

我在补充 collectionView 单元格中创建了一个按钮作为标题,并向其添加了一个带有目标的按钮,但点击时它不会触发该功能。我究竟做错了什么?

下面是我在单元格类中创建的按钮及其目标函数。

let dummyButton :UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Dummy", for: .normal)
    button.layer.cornerRadius = 3
    button.layer.borderWidth = 1
    button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
    button.tintColor = UIColor.brown
    button.addTarget(self, action: #selector(handleTrash), for: .touchUpInside)
    return button
}() 


@objc func handleTrash (){
    print("It worked this time around so what was going on?")
}

我在 collectionView Cell 子类中编写了所有这些。请帮忙

标签: swiftuibuttonuicollectionviewcellswift5addtarget

解决方案


我找到了解决方案。我必须将按钮声明为惰性变量。


推荐阅读