addTarget不适用于UICollectionViewCell中的按钮

时间:2019-06-08 20:46:27

标签: ios swift uibutton

单击按钮时,不会调用选择器。 单元格只有两个,一个是图像,另一个是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()
  }
}

1 个答案:

答案 0 :(得分:1)

let removeButton更改为lazy var removeButton

self在调用init之前不存在。在self常量中向let添加目标时,是在调用init之前定义它。

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