Skip to content

Instantly share code, notes, and snippets.

@saoudrizwan
Last active March 4, 2024 06:45
Show Gist options
  • Save saoudrizwan/548aa90be174320fbaa6b3e71f01f6ae to your computer and use it in GitHub Desktop.
Save saoudrizwan/548aa90be174320fbaa6b3e71f01f6ae to your computer and use it in GitHub Desktop.
Easily create tap gesture recognizers for any view using closures as actions instead of selectors.
import UIKit
extension UIView {
// In order to create computed properties for extensions, we need a key to
// store and access the stored property
fileprivate struct AssociatedObjectKeys {
static var tapGestureRecognizer = "MediaViewerAssociatedObjectKey_mediaViewer"
}
fileprivate typealias Action = (() -> Void)?
// Set our computed property type to a closure
fileprivate var tapGestureRecognizerAction: Action? {
set {
if let newValue = newValue {
// Computed properties get stored as associated objects
objc_setAssociatedObject(self, &AssociatedObjectKeys.tapGestureRecognizer, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
get {
let tapGestureRecognizerActionInstance = objc_getAssociatedObject(self, &AssociatedObjectKeys.tapGestureRecognizer) as? Action
return tapGestureRecognizerActionInstance
}
}
// This is the meat of the sauce, here we create the tap gesture recognizer and
// store the closure the user passed to us in the associated object we declared above
public func addTapGestureRecognizer(action: (() -> Void)?) {
self.isUserInteractionEnabled = true
self.tapGestureRecognizerAction = action
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture))
self.addGestureRecognizer(tapGestureRecognizer)
}
// Every time the user taps on the UIImageView, this function gets called,
// which triggers the closure we stored
@objc fileprivate func handleTapGesture(sender: UITapGestureRecognizer) {
if let action = self.tapGestureRecognizerAction {
action?()
} else {
print("no action")
}
}
}
@ThoseGuysInTown
Copy link

thank you for this!

@0xfeedface1993
Copy link

Thank you verry much!

@onuryah
Copy link

onuryah commented Nov 10, 2021

Thank you so much!!

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