let btn = UIButton()
btn.on(.TouchUpInside) { sender, _ in
sender.setTitle(titleLabel.text = "Pushed !!", forState: .Normal)
}
Any ideas?
Added: to reply the @nhgrif answer:
Why I did not implement the sender
only version like this:
func on<T: UIControl>(events:UIControlEvents, _ callback: T -> Void) -> EventHandlerId {
assert(self.isKindOfClass(T), "The handler must receive \(NSStringFromClass(self.dynamicType)) or UIControl")
return self._on(events, EventHandler({ sender, _ in callback(sender as T) }, oneshot: true))
}
That is because of a purely technical problem: It conflict with () -> Void
version.
btn.on(.TouchUpInside) { return } // OK: () -> Void
btn.on(.TouchUpInside) { (sender: UIButton) in return } // OK: T -> Void
btn.on(.TouchUpInside) { sender in return } // NG: () -> Void
In the last case, the compiler infers the type of sender
as ()
:(
And why I declared EventHandler
as private
, that is I don't want users do like this:
let handler = UIControl.EventHandler({ ... }, oneshot: true)
btn.on(.TouchUpInside, handler)
btn.on(.TouchDown, handler)
btn.off(handler)
With my current code, .off()
removes the handler from .AllEvents
, and from associated objects. There is no way to remove it from specific event. Maybe, if we do want to do that, we can remember the registered events and handle them, but It's too much I think. Moreover, for such use case, we can simply use addTarget()
and removeTarget()
with custom handler object.