如何动态地向 UIButton 添加动作

How to dynamically add an action to a UIButton

我注意到我有很多功能可以在我的一个视图控制器中动态添加按钮,这显然违反了 DRY 原则。

为了解决这个问题,我写了一个命中一切的 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 没有 Selector 的内置实现,你传递一个字符串,字符串文字被类型推断为 Selector(就像输入数字字面量将同时作为 int、float、NSNumber 等一样工作)。