[英]Assign 'action' dynamically in uibutton.addTarget
請耐心等待,因為我剛開始學習-4周。
我在fileA.swift中創建了以下2個函數
func custombttn(theSelector:Selector)-> UIButton{
let bttn = UIButton(frame: CGRect(x:20, y:400, width:200, height:30))
bttn.setTitle("tap this button", for: UIControlState.normal)
bttn.backgroundColor = UIColor.black
bttn.setTitleColor(UIColor.magenta, for: UIControlState.normal)
bttn.addTarget(bttn, action: theSelector, for: UIControlEvents.touchUpInside)
return bttn
}
func customtxtfld() -> UITextField{
let txtField = UITextField(frame: CGRect(x:20, y:360, width:200, height:30))
txtField.borderStyle = UITextBorderStyle.roundedRect
txtField.backgroundColor = UIColor.magenta
txtField.placeholder = "Do you like me now..?"
return txtField
}
custombttn(theSelector:Selector)
背后的原因是,我想將函數動態傳遞給我的viewcontroller文件中的按鈕。
現在,移動fileB.swift,我有以下代碼...
class TabOneViewController: UIViewController{
let txt = customtxtfld()
let bttn = custombttn(theSelector: #selector(updatetxt))
override func loadView() {
super.loadView()
view.addSubview(txt)
view.addSubview(bttn)
}
func updatetxt(){
txt.text = "hello, you!"
}
}
在這里,事情變得棘手,當我嘗試構建時,我沒有收到任何錯誤(甚至沒有警告)。 但是,當我運行該應用程序並點擊bttn
中的bttn時 ,在運行時出現以下錯誤:
由於未捕獲的異常'NSInvalidArgumentException'而終止應用程序,原因:'-[UIButton updatetxt]:無法識別的選擇器已發送到實例0x7f8453415670'
如果我想在我的fileB.swift中有2個或更多函數要動態分配給addTarget的操作部分, 有什么方法可以將選擇器動態傳遞給按鈕。
感謝您的時間和協助。 如果需要進一步說明,請告訴我。
是的你可以。 這里的問題是您將按鈕本身傳遞為操作的目標。 添加動作時只需傳遞正確的目標即可,在這種情況下,這就是您的視圖控制器的實例。
它崩潰是因為您的按鈕目標錯誤。
func custombttn(target:Any, theSelector:Selector)-> UIButton{
let bttn = UIButton(frame: CGRect(x:20, y:400, width:200, height:30))
bttn.setTitle("tap this button", for: UIControlState.normal)
bttn.backgroundColor = UIColor.black
bttn.setTitleColor(UIColor.magenta, for: UIControlState.normal)
bttn.addTarget(target, action: theSelector, for: UIControlEvents.touchUpInside)
return bttn
}
像這樣使用
class TabOneViewController: UIViewController{
let txt = customtxtfld()
override func loadView() {
super.loadView()
view.addSubview(txt)
let bttn = custombttn(target:self, theSelector: #selector(updatetxt))
view.addSubview(bttn)
}
func updatetxt(){
txt.text = "hello, you!"
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.