I was just wondering if it was possible to pass a function to a button action (which is usually a selector).
For example, normally I'd say:
UIBarButtonItem(title: "Press", style: .Done, target: self, action: "functionToCall") func functionToCall() { // Do something }
But I was wondering if it's possible to do something like:
UIBarButtonItem(title: "Press", style: .Done, target: self, action: { // Do Something })
Reason I want to do this is because my function is super simple and it seems like it would be neater and more Swift-like what with the emphasis they are placing on closures.
Here's an updated solution for Swift 3.
class BlockBarButtonItem: UIBarButtonItem { private var actionHandler: (() -> Void)? convenience init(title: String?, style: UIBarButtonItem.Style, actionHandler: (() -> Void)?) { self.init(title: title, style: style, target: nil, action: #selector(barButtonItemPressed)) self.target = self self.actionHandler = actionHandler } convenience init(image: UIImage?, style: UIBarButtonItem.Style, actionHandler: (() -> Void)?) { self.init(image: image, style: style, target: nil, action: #selector(barButtonItemPressed)) self.target = self self.actionHandler = actionHandler } @objc func barButtonItemPressed(sender: UIBarButtonItem) { actionHandler?() } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With