Swift:以UICollectionViewCell中的IndexPath中的多个UIButton以编程方式,nextTarget不会单击

我以编程方式在UICollectionViewCell的indexPath中创build了多个UIButton。 现在我想要打印“点击添加到collections夹”,但点击UIButton后,它不打印任何东西。 UIButton不会查看除addTarget函数之外的所有内容,而不是单击。

 import UIKit //**UICollectionViewCell** class DescriptionCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { override init(frame: CGRect) { super.init(frame: frame) setupCell() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } lazy var addToCart: UIButton = { let btn = UIButton() btn.setTitle("Add to favourite", for: .normal) btn.isUserInteractionEnabled = true btn.setTitleColor(.white, for: .normal) btn.backgroundColor = UIColor.orange btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 8) btn.titleLabel?.textAlignment = .right // addToCart not click btn.addTarget(self, action: #selector(addToCartTarget), for: .touchUpInside) btn.layer.cornerRadius = 12 return btn }() func setupCell() { addSubview(addToCart) addConstraintsWithFormat("H:|-80-[v0]-80-|", views: addToCart) addConstraintsWithFormat("V:|-380-[v0(25)]|", views: addToCart) } func addToCartTarget() { print("you clicked add to favourite") } } 

在这里输入图像说明

尝试使用如下框架初始化button:

 let btn = UIButton(frame: CGRect(x: 10, y: 10, width: 50, height: 20))