I have a function...
func MyFunc (_ sender: AnyObject) {
let n = sender.tag! //do stuff with 'n'
}
which I connect when creating my NewButton...
NewButton.addTarget(self, action: #selector(Main.MyFunc(_:)), for: .touchUpInside)
I'd like to call MyFunc
in other areas of my code without a sender. Is it possible to .addTarget to a Button without using sender?
Such as....
NewButton.addTarget(self, action: #selector(Main.MyFunc(n: 5)), for: .touchUpInside)
and...
func MyFunc (n: Int) {
//do stuff with 'n'
}
I know one solution would be a routing function like...
func router (_ sender: AnyObject) {
MyFunc(n: sender.tag!)
}
But I'm wondering if there's a more elegant way.
Since the function takes a sender of type AnyObject
you can use any object as an argument to the function. You will then just need to conditionally cast it to the type you want.
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
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加