-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
UIView-Extensions.swift
68 lines (55 loc) · 1.67 KB
/
UIView-Extensions.swift
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import UIKit
private func swizzle(_ v: UIView.Type) {
[
(#selector(v.traitCollectionDidChange(_:)), #selector(v.ksr_traitCollectionDidChange(_:))),
(#selector(v.didMoveToSuperview), #selector(v.ksr_didMoveToSuperview))
]
.forEach { original, swizzled in
guard let originalMethod = class_getInstanceMethod(v, original),
let swizzledMethod = class_getInstanceMethod(v, swizzled) else { return }
let didAddViewDidLoadMethod = class_addMethod(
v,
original,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod)
)
if didAddViewDidLoadMethod {
class_replaceMethod(
v,
swizzled,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod)
)
} else {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
}
private var hasSwizzled = false
extension UIView {
public final class func doBadSwizzleStuff() {
guard !hasSwizzled else { return }
hasSwizzled = true
swizzle(self)
}
open override func awakeFromNib() {
super.awakeFromNib()
self.bindViewModel()
}
@objc open func bindStyles() {}
@objc open func bindViewModel() {}
public static var defaultReusableId: String {
return self.description()
.components(separatedBy: ".")
.dropFirst()
.joined(separator: ".")
}
@objc internal func ksr_traitCollectionDidChange(_ previousTraitCollection: UITraitCollection) {
self.ksr_traitCollectionDidChange(previousTraitCollection)
self.bindStyles()
}
@objc internal func ksr_didMoveToSuperview() {
self.ksr_didMoveToSuperview()
self.bindStyles()
}
}