[英]Swift: Apply “addTarget” to a UIButton in a different class
我有一類叫做RecordViewFooter
在那里我創建UIButton
稱為microphoneButton
。 我添加為subview
,它看起來很漂亮。
但是,選擇此按鈕后,我需要向ViewController
添加一些內容作為subview
。 所以我在ViewController
做到了這一點:
RecordViewFooter().microphoneButton.addTarget(self, action: "microphoneButtonPressed", forControlEvents: UIControlEvents.TouchUpInside)
}
func microphoneButtonPressed(){
print("microphone button pressed")
volumeAdjuster = VolumeAdjusterView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height))
self.view.addSubview(volumeAdjuster!)
}
我不知道為什么當選擇按鈕時它不會調用該函數。 有什么想法嗎?
嘗試以下修改的代碼:
RecordViewFooter().microphoneButton.addTarget(self, action: "microphoneButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
func microphoneButtonPressed(button:UIButton){
print("microphone button pressed")
volumeAdjuster = VolumeAdjusterView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height))
self.view.addSubview(volumeAdjuster!)
}
您可以通過實施以下解決方案來解決該問題:
首先准備RecordViewFooter類的對象。 像這里,我創建RecordViewFooter()類的對象。
var popViewObj = UINib(nibName: "RecordViewFooter", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! RecordViewFooter
現在在完成子視圖后編寫此代碼。
popViewObj.microphoneButton.addTarget(self, action: "microphoneButtonPressed:",forControlEvents: UIControlEvents.TouchUpInside)
現在,在您的代碼中添加所選按鈕事件:
func microphoneButtonPressed(sender: UIButton) { print("microphone button pressed") // Do Whatever u want... }
它會正常工作..我希望你會用這段代碼。
我知道了。 我必須從要引用全局變量的類中創建一個對象。 然后執行以下操作:
objectFromClass.globalVariable.addTarget(self, action: "buttonPressed", forControlEvents: UIControlEvents.TouchUpInside)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.