From 994d931efaebf9f30e7470b26a05965cda9208cd Mon Sep 17 00:00:00 2001 From: Michael Rebello Date: Wed, 19 Jul 2017 17:45:40 -0700 Subject: [PATCH] Add `replaceEventHandler` to UIControl (#26) Adds a `replaceEventHandler` function to `UIControl` to act as a convenience function for removing event handlers and adding a new one. --- LambdaKit.podspec | 2 +- Source/UIControl+LambdaKit.swift | 18 +++++++++++++++--- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/LambdaKit.podspec b/LambdaKit.podspec index 3ea0d1a..be23fd1 100644 --- a/LambdaKit.podspec +++ b/LambdaKit.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'LambdaKit' - s.version = '0.2.0' + s.version = '0.2.1' s.license = 'MIT' s.summary = 'Closures on most used UIKit methods' s.homepage = 'https://github.com/Reflejo/LambdaKit' diff --git a/Source/UIControl+LambdaKit.swift b/Source/UIControl+LambdaKit.swift index a5ec742..2cc9fbd 100644 --- a/Source/UIControl+LambdaKit.swift +++ b/Source/UIControl+LambdaKit.swift @@ -62,7 +62,7 @@ extension UIControl { set { objc_setAssociatedObject(self, &associatedEventHandle, newValue, - objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) + objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } @@ -70,7 +70,7 @@ extension UIControl { /// /// - parameter controlEvents: A bitmask specifying the control events for which the action message is /// sent. - /// - parameter handler: A block representing an action message, with an argument for the sender. + /// - parameter handler: A closure representing an action message, with an argument for the sender. public func addEventHandler(forControlEvents controlEvents: UIControlEvents, handler: @escaping LKControlHandler) { @@ -99,8 +99,20 @@ extension UIControl { self.events?[event] = nil for wrapper in wrappers { self.removeTarget(wrapper, action: #selector(ControlWrapper.invoke(_:)), - for: UIControlEvents(rawValue: event)) + for: UIControlEvents(rawValue: event)) } } } + + /// Convenience function for setting a control's handler. Removes all other handlers for the provided + /// events. + /// + /// - parameter controlEvents: A bitmask specifying the control events that the handler will replace. + /// - parameter handler: A closure representing an action message, with an argument for the sender. + public func setEventHandler(forControlEvents controlEvents: UIControlEvents, + handler: @escaping LKControlHandler) + { + self.removeEventHandlers(forControlEvents: controlEvents) + self.addEventHandler(forControlEvents: controlEvents, handler: handler) + } }