如何在没有发件人的情况下将目标添加到 UIButton

How to addTarget to UIButton without sender

我有一个功能...

func MyFunc (_ sender: AnyObject) { 
    let n = sender.tag! //do stuff with 'n'
}

我在创建 NewButton 时连接...

NewButton.addTarget(self, action: #selector(Main.MyFunc(_:)), for: .touchUpInside)

我想在我代码的其他区域调用 MyFunc 而无需发件人。是否可以在不使用发件人的情况下将 .addTarget 添加到按钮?

比如....

NewButton.addTarget(self, action: #selector(Main.MyFunc(n: 5)), for: .touchUpInside)

和...

func MyFunc (n: Int) {
    //do stuff with 'n'
}

我知道一个解决方案是路由功能,例如...

func router (_ sender: AnyObject) {
    MyFunc(n: sender.tag!)
}

但我想知道是否有更优雅的方式。

由于该函数采用 AnyObject 类型的发送者,您可以使用任何对象作为该函数的参数。然后你只需要有条件地将它转换为你想要的类型。

let button = UIButton()
button.addTarget(self, action: #selector(touched(_:)), for: .touchUpInside)

touched(1 as AnyObject) // Works

@objc func touched(_ sender: AnyObject) {
    if let casted = sender as? Int {
        // Do something with casted as an Int
    } else if let casted = sender as? UIButton {
        // do something with casted.tag
    }
}