Created
September 24, 2014 09:04
-
-
Save advantis/f27d54cb1b7f58f3de69 to your computer and use it in GitHub Desktop.
C#-inspired event handling in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
typealias EventHandler = (AnyObject) -> Void | |
class Event { | |
var handlers: [EventHandler] = [] | |
func subscribe(handler: EventHandler) { | |
handlers.append(handler) | |
} | |
dynamic func invoke(sender: AnyObject) { | |
handlers.map({$0(sender)}) | |
} | |
} | |
func +=(event: Event, handler: EventHandler) { | |
event.subscribe(handler) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension UIControl { | |
struct ControlEvents { | |
static let TouchUpInside = "TouchUpInside" | |
} | |
var TouchUpInside: Event { | |
return objc_getAssociatedObject(self, ControlEvents.TouchUpInside) as Event! ?? { | |
let event = Event() | |
self.addTarget(event, action: "invoke:", forControlEvents:UIControlEvents.TouchUpInside) | |
objc_setAssociatedObject(self, ControlEvents.TouchUpInside, event, UInt(OBJC_ASSOCIATION_RETAIN)) | |
return event | |
}() | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ViewController: UIViewController { | |
@IBOutlet | |
weak var button: UIButton! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
button.TouchUpInside += action | |
button.TouchUpInside += {sender in | |
println("closure: \(sender)") | |
} | |
} | |
func action(sender: AnyObject) { | |
println("method: = \(sender)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How does this work with unsubscribing?