Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift use selector argument like a closure

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.

like image 613
Chris Byatt Avatar asked Nov 11 '15 14:11

Chris Byatt


Video Answer


1 Answers

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?()     } } 
like image 109
David Avatar answered Sep 20 '22 23:09

David