Advertisement
anhhtz

Untitled

Sep 19th, 2019
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.86 KB | None | 0 0
  1. import UIKit
  2.  
  3. extension UIView {
  4.    
  5.     // In order to create computed properties for extensions, we need a key to
  6.     // store and access the stored property
  7.     fileprivate struct AssociatedObjectKeys {
  8.         static var tapGestureRecognizer = "MediaViewerAssociatedObjectKey_mediaViewer"
  9.     }
  10.    
  11.     fileprivate typealias Action = (() -> Void)?
  12.    
  13.     // Set our computed property type to a closure
  14.     fileprivate var tapGestureRecognizerAction: Action? {
  15.         set {
  16.             if let newValue = newValue {
  17.                 // Computed properties get stored as associated objects
  18.                 objc_setAssociatedObject(self, &AssociatedObjectKeys.tapGestureRecognizer, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
  19.             }
  20.         }
  21.         get {
  22.             let tapGestureRecognizerActionInstance = objc_getAssociatedObject(self, &AssociatedObjectKeys.tapGestureRecognizer) as? Action
  23.             return tapGestureRecognizerActionInstance
  24.         }
  25.     }
  26.    
  27.     // This is the meat of the sauce, here we create the tap gesture recognizer and
  28.     // store the closure the user passed to us in the associated object we declared above
  29.     public func addTapGestureRecognizer(action: (() -> Void)?) {
  30.         self.isUserInteractionEnabled = true
  31.         self.tapGestureRecognizerAction = action
  32.         let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture))
  33.         self.addGestureRecognizer(tapGestureRecognizer)
  34.     }
  35.    
  36.     // Every time the user taps on the UIImageView, this function gets called,
  37.     // which triggers the closure we stored
  38.     @objc fileprivate func handleTapGesture(sender: UITapGestureRecognizer) {
  39.         if let action = self.tapGestureRecognizerAction {
  40.             action?()
  41.         } else {
  42.             print("no action")
  43.         }
  44.     }
  45.    
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement