Last active
March 4, 2024 06:45
-
-
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.
This file contains 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
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") | |
} | |
} | |
} |
Thank you verry much!
Thank you so much!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you for this!