2017-07-15 89 views
0

我正在向集合视图单元格的自定义类中添加一个按钮,但无法使其点击。单击CollectionViewCell中的按钮

下面是我在单元格的自定义类声明按钮:

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和自我,但都给出了相同的结果,wh ich是不可点击的按钮。

欢迎任何建议。

回答

1

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

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

添加作为一个子视图按钮,您添加目标的不同实例的按钮。您必须使用lazy varshareBtn类似如下:

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

+0

是什么?你是对的。为什么会迅速做到这一点,为什么要创建它的新实例,我不明白。谢谢 – fullMoon

0

该按钮位于父视图控制器中添加的页面控制视图之下。此外,我需要添加子视图到小区后致电操作方法:

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