单击 CollectionViewCell 中的按钮

Clicking A Button In A CollectionViewCell

我正在向集合视图单元格的自定义按钮添加一个按钮 class,但无法单击它。

下面是我在自定义单元格中声明按钮的方式 class:

let shareBtn: UIButton = {
    let roundBtn = UIButton()
    roundBtn.frame = CGRect(x: 0, y: 0, width: 70, height: 70)
    roundBtn.layer.cornerRadius = 35
    roundBtn.layer.shadowOpacity = 0.25
    roundBtn.layer.shadowRadius = 2
    roundBtn.setImage(UIImage(named: "share"), for: .normal)
    roundBtn.addTarget(self, action: #selector(shareAction(button:)), for: .touchUpInside)
    roundBtn.isUserInteractionEnabled = true
    roundBtn.isEnabled = true

    return roundBtn
}()

这里是选择器调用的方法:

func shareAction(button: UIButton){
    print("shareAction")
}

这里是我如何在 init

中添加按钮
override init(frame: CGRect) {
    super.init(frame: frame)

    contentView.addSubview(shareBtn)

    shareBtn.translatesAutoresizingMaskIntoConstraints = false
    shareBtn.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -100).isActive = true
    shareBtn.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
    shareBtn.widthAnchor.constraint(equalToConstant: 70).isActive = true
    shareBtn.heightAnchor.constraint(equalToConstant: 70).isActive = true

我尝试将按钮添加到两者 - contentView 和 self,但两者都给出相同的结果,即无法点击的按钮。

欢迎提出任何建议。

该按钮位于父视图控制器中添加的页面控制视图下。我还需要在将子视图添加到单元格后调用操作方法:

 addSubview(shareBtn)
 shareBtn.addTarget(self, action: #selector(shareAction(button:)), for: .touchUpInside)

每当您访问 shareBtn 时,您创建按钮的方式总是在创建一个新实例,因为它是一个计算变量。这就是为什么当你写这个:

addSubview(shareBtn)
 shareBtn.addTarget(self, action: #selector(shareAction(button:)), for: .touchUpInside)

您添加为子视图的按钮和您添加目标的按钮是不同的实例。您必须为 shareBtn 使用 lazy var,如下所示:

lazy var shareBtn: UIButton = {
    let roundBtn = UIButton()
    roundBtn.frame = CGRect(x: 0, y: 0, width: 70, height: 70)
    roundBtn.layer.cornerRadius = 35
    roundBtn.layer.shadowOpacity = 0.25
    roundBtn.layer.shadowRadius = 2
    roundBtn.setImage(UIImage(named: "share"), for: .normal)
    roundBtn.addTarget(self, action: #selector(shareAction(button:)), for: .touchUpInside)
    roundBtn.isUserInteractionEnabled = true
    roundBtn.isEnabled = true

    return roundBtn
}()

这样,当您第一次访问它时,只会创建一个实例并将其分配给 shareBtn,所有后续访问都将使用同一个实例。