Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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")
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement