2017-07-15 30 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)