Skip to content

Instantly share code, notes, and snippets.

@Moximillian
Last active February 17, 2021 03:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Moximillian/5f6d60e2cd1222e557547a42558669ae to your computer and use it in GitHub Desktop.
Save Moximillian/5f6d60e2cd1222e557547a42558669ae to your computer and use it in GitHub Desktop.
Swift protocol and extensions for adding support to closures in UIKit classes. Extension support for UIButton, UIGestureRecognizer, UIBarButtonItem etc. Swift 3.0.
// Free to copy, use and modify for all types of software projects
import UIKit
// ************** Protocol ***************
/// Closurable protocol
protocol Closurable: class {}
// restrict protocol to only classes => can refer to the class instance in the protocol extension
extension Closurable {
// Create container for closure, store it and return it
func getContainer(for closure: @escaping (Self) -> Void) -> ClosureContainer<Self> {
weak var weakSelf = self
let container = ClosureContainer(closure: closure, caller: weakSelf)
// store the container so that it can be called later, we do not need to explicitly retrieve it.
objc_setAssociatedObject(self, Unmanaged.passUnretained(self).toOpaque(), container as AnyObject!, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return container
}
}
/// Container class for closures, so that closure can be stored as an associated object
final class ClosureContainer<T: Closurable> {
var closure: (T) -> Void
var caller: T?
init(closure: @escaping (T) -> Void, caller: T?) {
self.closure = closure
self.caller = caller
}
// method for the target action, visible to UIKit classes via @objc
@objc func processHandler() {
if let caller = caller {
closure(caller)
}
}
// target action
var action: Selector { return #selector(processHandler) }
}
// ************** UIKit extensions ***************
/// extension for UIButton - actions with closure
extension UIButton: Closurable {
func addTarget(forControlEvents: UIControlEvents = .touchUpInside, closure: @escaping (UIButton) -> Void) {
let container = getContainer(for: closure)
addTarget(container, action: container.action, for: forControlEvents)
}
}
/// extension for UIPageControl - actions with closure
extension UIPageControl: Closurable {
func addTarget(forControlEvents: UIControlEvents = .valueChanged, closure: @escaping (UIPageControl) -> Void) {
let container = getContainer(for: closure)
addTarget(container, action: container.action, for: forControlEvents)
}
}
/// extension for UIGestureRecognizer - actions with closure
extension UIGestureRecognizer: Closurable {
convenience init(closure: @escaping (UIGestureRecognizer) -> Void) {
self.init()
let container = getContainer(for: closure)
addTarget(container, action: container.action)
}
}
/// extension for UIBarButtonItem - actions with closure
extension UIBarButtonItem: Closurable {
convenience init(image: UIImage?, style: UIBarButtonItemStyle = .plain, closure: @escaping (UIBarButtonItem) -> Void) {
self.init(image: image, style: style, target: nil, action: nil)
let container = getContainer(for: closure)
target = container
action = container.action
}
convenience init(title: String?, style: UIBarButtonItemStyle = .plain, closure: @escaping (UIBarButtonItem) -> Void) {
self.init(title: title, style: style, target: nil, action: nil)
let container = getContainer(for: closure)
target = container
action = container.action
}
}
@Moximillian
Copy link
Author

Moximillian commented Mar 29, 2016

EXAMPLE USAGE

let button = UIButton()

button.addTarget() { button in
print("Button clicked")
}

@Moximillian
Copy link
Author

Note: currently this supports adding ONE target per instance of an UI element. If you need more than one per instance, you can do one with this closure and others the old way.

@Moximillian
Copy link
Author

Moximillian commented Jun 5, 2016

Version 2.0 in Gist. Revised handling of target actions => less code. This is in Swift 3.0. Backporting to Swift 2.2 is left as an exercise to the reader :)

@radianttap
Copy link

This protocol has serious issue - it renders UIButton and other elements that adopt it, into non-event sources. Thus all buttons lose the ability to use regular target-action mechanism, say by connecting actions in Interface Builder.
Not sure is this something that can be fixed...

@Moximillian
Copy link
Author

Moximillian commented Feb 4, 2017

Hi @radianttap, this extension is purely additive, it does not override any standard APIs. I have tested that IBAction as well as regular addTarget() work fine together with this extension, when added to the same object in the Storyboard.

... however, adding any kind of protocol conformance to UIButton or similar, renders it impossible to drag any actions for those elements inside Interface builder. TouchUpInside and similar are simply not available. The workaround is to comment out the conformance, drag the actions, and then un-comment the conformance. After that all works fine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment