我注意到我有很多函数可以在我的 View Controller 之一中动态添加按钮,这显然违背了 DRY 原则。
为了解决这个问题,我编写了一个 hit-everything configureButton
函数:
func configureButton (button: UIButton, action: String, title: String, pos: [CGFloat]) {
button.addTarget(self, action: action,
forControlEvents: UIControlEvents.TouchUpInside)
// ^ throws an error
// button.addTarget(self, action: "goToScanner",
// forControlEvents: UIControlEvents.TouchUpInside)
/* configure everything else */
self.view.addSubview(button)
}
当我有无数不同的功能时,我只是写了类似的东西
button.addTarget(self, action: "goToScanner", // <-- note the string
forControlEvents: UIControlEvents.TouchUpInside)
在每个函数中,其中 "goToScanner"
是我想要点击调用的函数。
我希望能够动态地将 button.addTarget
的操作参数传递给 configureButton
:
configureButton(scanButton, action: "goToScanner", title: "Scan", pos: [36.0, 300])
我尝试传递一个闭包 () -> ()
,但这不起作用。
如何解决这个问题?
最佳答案
你的方法应该是
func configureButton (button: UIButton, action: Selector, title: String, pos: [CGFloat])
注意它如何使用Selector
而不是String
。
这是因为 Swift 没有内置的选择器
实现,您传递一个字符串,并且字符串文字被类型推断为选择器
(就像输入数字文字将作为 int、float、NSNumber 等一样工作)。
关于ios - 如何动态向 UIButton 添加操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30554577/