Blame view

App/camera/ALCameraLib/Utilities/UIButtonExtensions.swift 1.35 KB
1341bf603   Trịnh Văn Quân   version 1.1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
  //
  //  UIButtonExtensions.swift
  //  ALCameraViewController
  //
  //  Created by Alex Littlejohn on 2016/03/26.
  //  Copyright © 2016 zero. All rights reserved.
  //
  
  import UIKit
  
  typealias ButtonAction = () -> Void
  
  extension UIButton {
      
      private struct AssociatedKeys {
          static var ActionKey = "ActionKey"
      }
      
      private class ActionWrapper {
          let action: ButtonAction
          init(action: @escaping ButtonAction) {
              self.action = action
          }
      }
      
      var action: ButtonAction? {
          set(newValue) {
              removeTarget(self, action: #selector(performAction), for: .touchUpInside)
              var wrapper: ActionWrapper? = nil
              if let newValue = newValue {
                  wrapper = ActionWrapper(action: newValue)
                  addTarget(self, action: #selector(performAction), for: .touchUpInside)
              }
              
              objc_setAssociatedObject(self, &AssociatedKeys.ActionKey, wrapper, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
          }
          get {
              guard let wrapper = objc_getAssociatedObject(self, &AssociatedKeys.ActionKey) as? ActionWrapper else {
                  return nil
              }
              
              return wrapper.action
          }
      }
      
      func performAction() {
          guard let action = action else {
              return
          }
  
          action()
      }
  }