mikelily

clickImageView

Jun 21st, 2019
332
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.42 KB | None | 0 0
  1. //
  2. //  clickImageView.swift
  3. //  Andromeda
  4. //
  5. //  Created by 蒼月喵 on 2019/6/21.
  6. //  Copyright © 2019 蒼月喵. All rights reserved.
  7. //
  8.  
  9. import Foundation
  10. import UIKit
  11.  
  12. public typealias SimpleClosure = (() -> ())
  13. private var tappableKey : UInt8 = 0
  14. private var actionKey : UInt8 = 1
  15.  
  16. extension UIImageView {
  17.    
  18.     @objc var callback: SimpleClosure {
  19.         get {
  20.             return objc_getAssociatedObject(self, &actionKey) as! SimpleClosure
  21.         }
  22.         set {
  23.             objc_setAssociatedObject(self, &actionKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  24.         }
  25.     }
  26.    
  27.     var gesture: UITapGestureRecognizer {
  28.         get {
  29.             return UITapGestureRecognizer(target: self, action: #selector(tapped))
  30.         }
  31.     }
  32.    
  33.     var tappable: Bool! {
  34.         get {
  35.             return objc_getAssociatedObject(self, &tappableKey) as? Bool
  36.         }
  37.         set(newValue) {
  38.             objc_setAssociatedObject(self, &tappableKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
  39.             self.addTapGesture()
  40.         }
  41.     }
  42.    
  43.     fileprivate func addTapGesture() {
  44.         if (self.tappable) {
  45.             self.gesture.numberOfTapsRequired = 1
  46.             self.isUserInteractionEnabled = true
  47.             self.addGestureRecognizer(gesture)
  48.         }
  49.     }
  50.    
  51.     @objc private func tapped() {
  52.         callback()
  53.     }
  54.    
  55. }
Advertisement
Add Comment
Please, Sign In to add comment