请耐心等待,因为我是 swift -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)
是我想将函数动态传递给我的视图控制器文件中的按钮。
现在,移动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
in fileB.swift时,我在运行时收到以下错误:
由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[UIButton updatetxt]:无法识别的选择器发送到实例 0x7f8453415670”
如果我的 fileB.swift 中有 2 个或更多函数希望动态分配给 addTarget 的操作部分,有什么方法可以将选择器动态传递给按钮..?
感谢您的时间和帮助。如果我需要进一步解释,请告诉我。