繁体   English   中英

addTarget不适用于UICollectionViewCell中的按钮

[英]addTarget is not working for button in UICollectionViewCell

当我点击按钮时,选择器没有被调用。 单元格只有两个,一个是图像,另一个是UIButton。 以下是收集单元的代码。 还有其他方法可以添加方法吗?

class AttachmentCell: UICollectionViewCell {
   weak var delegate: AttachmentCellDelegate?

let removeButton: UIButton = {
    let button = UIButton(type: .custom)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setImage(UIImage(named: "close_icon"), for: .normal)
    button.addTarget(self, action: #selector(removeButtonTapped), for: .touchUpInside)
    button.isUserInteractionEnabled = true
    return button
}()

let imageView: UIImageView = {
    let imgView = UIImageView()
    imgView.contentMode = .scaleAspectFill
    imgView.clipsToBounds = true
    return imgView
}()

override init(frame: CGRect) {
    super.init(frame: frame)
    self.backgroundColor = UIColor.red
    self.isUserInteractionEnabled = true

    self.contentView.addSubview(imageView)
    imageView.isUserInteractionEnabled = true
    self.contentView.addSubview(removeButton)
    //self.addSubview(removeButton)

    imageView.snp.makeConstraints { (make) in
        make.leading.equalToSuperview()
        make.trailing.equalToSuperview()
        make.top.equalToSuperview()
        make.bottom.equalToSuperview()
    }

    removeButton.snp.makeConstraints { (make) in
        make.width.equalTo(40)
        make.height.equalTo(40)
        make.top.equalTo(imageView.snp.top).offset(-5)
        make.trailing.equalTo(self.imageView.snp.trailing).offset(5)
    }

    self.backgroundColor = UIColor.gray
}

  @objc func removeButtonTapped() {
     delegate?.didRemoveButtonTapped()
  }
}

let removeButton更改为lazy var removeButton

在调用init之前, self不存在。 当您在let常量中向self添加目标时,您需要在调用init之前对其进行定义。

或者,只需在init块中调用addTarget

暂无
暂无

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

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