/
UIView+Layout.swift
1562 lines (1459 loc) · 59.4 KB
/
UIView+Layout.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright © 2017 Schibsted. All rights reserved.
import UIKit
import WebKit
extension UIView: LayoutManaged {
/// The view controller that owns the view - used to access layout guides
var viewController: UIViewController? {
var controller: UIViewController?
var responder: UIResponder? = next
while responder != nil {
if let responder = responder as? UIViewController {
controller = responder
break
}
responder = responder?.next
}
return controller
}
/// Expression names and types
@objc open class var expressionTypes: [String: RuntimeType] {
var types = allPropertyTypes()
// TODO: support more properties
types["alpha"] = .cgFloat
types["contentScaleFactor"] = .cgFloat
types["contentMode"] = .uiViewContentMode
types["tintAdjustmentMode"] = .uiViewTintAdjustmentMode
if #available(iOS 11.0, *) {} else {
types["directionalLayoutMargins"] = .uiEdgeInsets
}
for key in ["top", "leading", "bottom", "trailing"] {
types["directionalLayoutMargins.\(key)"] = .cgFloat
}
types["semanticContentAttribute"] = .uiSemanticContentAttribute
// Layer properties
for (name, type) in (layerClass as! CALayer.Type).cachedExpressionTypes {
types["layer.\(name)"] = type
}
// AutoLayout support
types["contentHuggingPriority.horizontal"] = .uiLayoutPriority
types["contentHuggingPriority.vertical"] = .uiLayoutPriority
types["contentCompressionResistancePriority.horizontal"] = .uiLayoutPriority
types["contentCompressionResistancePriority.vertical"] = .uiLayoutPriority
// Explicitly disabled properties
for name in [
"autoresizingMask",
"bounds",
"frame",
"topAnchor",
"bottomAnchor",
"leftAnchor",
"rightAnchor",
"widthAnchor",
"heightAnchor",
"leadingAnchor",
"trailingAnchor",
] {
types[name] = .unavailable("Use top/left/width/height instead")
let name = "\(name)."
for key in types.keys where key.hasPrefix(name) {
types[key] = .unavailable("Use top/left/width/height instead")
}
}
for name in [
"firstBaselineAnchor",
"lastBaselineAnchor",
] {
types[name] = .unavailable("Use firstBaseline or lastBaseline instead")
}
for name in [
"center",
"centerXAnchor",
"centerYAnchor",
] {
types[name] = .unavailable("Use center.x or center.y instead")
}
for name in [
"needsDisplayInRect",
"layer.delegate",
] {
types[name] = .unavailable()
let name = "\(name)."
for key in types.keys where key.hasPrefix(name) {
types[key] = .unavailable()
}
}
// Private and read-only properties
for name in [
"size",
"origin",
"position",
] + [
"effectiveUserInterfaceLayoutDirection",
"safeAreaInsets",
] {
types[name] = nil
let name = "\(name)."
for key in types.keys where key.hasPrefix(name) {
types[key] = nil
}
}
#if arch(i386) || arch(x86_64)
for name in [
"allowsBaselineOffsetApproximation",
"animationInfo",
"charge",
"clearsContext",
"clipsSubviews",
"compositingMode",
"contentStretch",
"contentsPosition",
"customAlignmentRectInsets",
"customBaselineOffsetFromBottom",
"customFirstBaselineOffsetFromContentTop",
"customFirstBaselineOffsetFromTop",
"customScreenScale",
"deliversButtonsForGesturesToSuperview",
"deliversTouchesForGesturesToSuperview",
"edgesInsettingLayoutMarginsFromSafeArea",
"edgesPreservingSuperviewLayoutMargins",
"enabledGestures",
"fixedBackgroundPattern",
"frameOrigin",
"gesturesEnabled",
"interactionTintColor",
"invalidatingIntrinsicContentSizeAlsoInvalidatesSuperview",
"isBaselineRelativeAlignmentRectInsets",
"layoutMarginsFollowReadableWidth",
"maximumLayoutSize",
"minimumLayoutSize",
"needsDisplayOnBoundsChange",
"neverCacheContentLayoutSize",
"previewingSegueTemplateStorage",
"rotationBy",
"skipsSubviewEnumeration",
"viewTraversalMark",
"wantsDeepColorDrawing",
] {
types[name] = nil
let name = "\(name)."
for key in types.keys where key.hasPrefix(name) {
types[key] = nil
}
}
#endif
return types
}
/// Constructor argument names and types
@objc open class var parameterTypes: [String: RuntimeType] {
return [:]
}
/// Deprecated symbols
/// Key is the symbol name, value is the suggested replacement
/// Empty value string indicates no replacement available
@objc open class var deprecatedSymbols: [String: String] {
return [
"topLayoutGuide.length": "safeAreaInsets.top",
"bottomLayoutGuide.length": "safeAreaInsets.bottom",
]
}
/// The name of the String or NSAttributedString property to use for body text
/// Return nil to indicate that the view doesn't allow body text
@objc open class var bodyExpression: String? {
let types = cachedExpressionTypes
for key in ["attributedText", "attributedTitle", "text", "title"] {
if let type = types[key], case let .any(subtype) = type.kind,
subtype is String.Type || subtype is NSAttributedString.Type {
return key
}
}
return nil
}
/// Called to construct the view
@objc open class func create(with _: LayoutNode) throws -> UIView {
return self.init()
}
/// Default expressions to use when not specified
@objc open class var defaultExpressions: [String: String] {
return [:]
}
// Return the best available VC for computing the layout guide
var _layoutGuideController: UIViewController? {
let viewController = self.viewController
return viewController?.navigationController?.topViewController ??
viewController?.tabBarController?.selectedViewController ?? viewController
}
var _safeAreaInsets: UIEdgeInsets {
if #available(iOS 11.0, *) {
if let viewController = viewController {
// This is the root view of a controller, so we can use the inset value directly, as per
// https://developer.apple.com/documentation/uikit/uiview/2891103-safeareainsets
return viewController.view.safeAreaInsets
} else if let window = window {
return window.safeAreaInsets
}
}
return UIEdgeInsets(
top: _layoutGuideController?.topLayoutGuide.length ?? 0,
left: 0,
bottom: _layoutGuideController?.bottomLayoutGuide.length ?? 0,
right: 0
)
}
internal var _effectiveUserInterfaceLayoutDirection: UIUserInterfaceLayoutDirection {
if #available(iOS 10.0, *) {
return effectiveUserInterfaceLayoutDirection
} else {
return UIView.userInterfaceLayoutDirection(for: semanticContentAttribute)
}
}
// Set expression value
@objc open func setValue(_ value: Any, forExpression name: String) throws {
if #available(iOS 11.0, *) {} else {
let ltr = (_effectiveUserInterfaceLayoutDirection == .leftToRight)
switch name {
case "directionalLayoutMargins":
layoutMargins = value as! UIEdgeInsets
return
case "directionalLayoutMargins.top":
layoutMargins.top = value as! CGFloat
return
case "directionalLayoutMargins.leading":
if ltr {
layoutMargins.left = value as! CGFloat
} else {
layoutMargins.right = value as! CGFloat
}
return
case "directionalLayoutMargins.bottom":
layoutMargins.bottom = value as! CGFloat
return
case "directionalLayoutMargins.trailing":
if ltr {
layoutMargins.right = value as! CGFloat
} else {
layoutMargins.left = value as! CGFloat
}
return
case "layer.maskedCorners":
return // TODO: warn about unavailability
default:
break
}
}
switch name {
case "contentHuggingPriority.horizontal":
setContentHuggingPriority(value as! UILayoutPriority, for: .horizontal)
case "contentHuggingPriority.vertical":
setContentHuggingPriority(value as! UILayoutPriority, for: .vertical)
case "contentCompressionResistancePriority.horizontal":
setContentCompressionResistancePriority(value as! UILayoutPriority, for: .horizontal)
case "contentCompressionResistancePriority.vertical":
setContentCompressionResistancePriority(value as! UILayoutPriority, for: .vertical)
default:
try _setValue(value, ofType: type(of: self).cachedExpressionTypes[name], forKeyPath: name)
}
}
// Set expression value with animation (if applicable)
@objc open func setAnimatedValue(_ value: Any, forExpression name: String) throws {
let type = Swift.type(of: self).cachedExpressionTypes[name]
if try !_setValue(value, ofType: type, forKey: name, animated: true) {
try setValue(value, forExpression: name)
}
}
/// Get symbol value
@objc open func value(forSymbol name: String) throws -> Any {
switch name {
case "backgroundColor":
return backgroundColor ?? .clear
case "safeAreaInsets":
return _safeAreaInsets
case "safeAreaInsets.top":
return _safeAreaInsets.top
case "safeAreaInsets.left":
return _safeAreaInsets.left
case "safeAreaInsets.bottom":
return _safeAreaInsets.bottom
case "safeAreaInsets.right":
return _safeAreaInsets.right
case "topLayoutGuide.length": // TODO: deprecate this
return _layoutGuideController?.topLayoutGuide.length ?? 0
case "bottomLayoutGuide.length": // TODO: deprecate this
return _layoutGuideController?.bottomLayoutGuide.length ?? 0
case "contentHuggingPriority.horizontal":
return contentHuggingPriority(for: .horizontal)
case "contentHuggingPriority.vertical":
return contentHuggingPriority(for: .vertical)
case "contentCompressionResistancePriority.horizontal":
return contentCompressionResistancePriority(for: .horizontal)
case "contentCompressionResistancePriority.vertical":
return contentCompressionResistancePriority(for: .vertical)
default:
break
}
if #available(iOS 11.0, *) {} else {
let ltr = (_effectiveUserInterfaceLayoutDirection == .leftToRight)
switch name {
case "directionalLayoutMargins":
return layoutMargins
case "directionalLayoutMargins.top":
return layoutMargins.top
case "directionalLayoutMargins.leading":
return ltr ? layoutMargins.left : layoutMargins.right
case "directionalLayoutMargins.bottom":
return layoutMargins.bottom
case "directionalLayoutMargins.trailing":
return ltr ? layoutMargins.right : layoutMargins.left
case "effectiveUserInterfaceLayoutDirection":
return _effectiveUserInterfaceLayoutDirection
case "layer.maskedCorners":
return CACornerMask()
default:
break
}
}
return try _value(ofType: type(of: self).cachedExpressionTypes[name], forKeyPath: name) as Any
}
/// Called immediately before a child node is added
/// Returning false will cancel insertion of the node
@objc open func shouldInsertChildNode(_ node: LayoutNode, at _: Int) -> Bool {
return true
}
/// Called immediately after a child node is added
@objc open func didInsertChildNode(_ node: LayoutNode, at index: Int) {
if let viewController = self.viewController {
for controller in node.viewControllers {
viewController.addChild(controller)
}
}
if index > 0, let previous = node.parent?.children[index - 1].view {
insertSubview(node.view, aboveSubview: previous)
} else {
addSubview(node.view)
}
}
/// Called immediately before a child node is removed
// TODO: remove index argument as it isn't used
@objc open func willRemoveChildNode(_ node: LayoutNode, at _: Int) {
if node._view == nil { return }
for controller in node.viewControllers {
controller.removeFromParent()
}
node.view.removeFromSuperview()
}
/// Called immediately after layout has been updated
@objc open func didUpdateLayout(for _: LayoutNode) {}
}
extension UIImageView {
open override class var expressionTypes: [String: RuntimeType] {
var types = super.expressionTypes
types["animationImages"] = .array(of: .uiImage)
types["highlightedAnimationImages"] = .array(of: .uiImage)
#if arch(i386) || arch(x86_64)
// Private properties
for name in [
"adjustsImageWhenAncestorFocused",
"cGImageRef",
"drawMode",
"masksFocusEffectToContents",
] {
types[name] = nil
}
#endif
return types
}
open override func setValue(_ value: Any, forExpression name: String) throws {
switch name {
case "isAnimating":
switch (value as! Bool, isAnimating) {
case (true, false):
startAnimating()
case (false, true):
stopAnimating()
case (true, true), (false, false):
break
}
default:
try super.setValue(value, forExpression: name)
}
}
}
private let controlEvents: [String: UIControl.Event] = [
"touchDown": .touchDown,
"touchDownRepeat": .touchDownRepeat,
"touchDragInside": .touchDragInside,
"touchDragOutside": .touchDragOutside,
"touchDragEnter": .touchDragEnter,
"touchDragExit": .touchDragExit,
"touchUpInside": .touchUpInside,
"touchUpOutside": .touchUpOutside,
"touchCancel": .touchCancel,
"valueChanged": .valueChanged,
"primaryActionTriggered": .primaryActionTriggered,
"editingDidBegin": .editingDidBegin,
"editingChanged": .editingChanged,
"editingDidEnd": .editingDidEnd,
"editingDidEndOnExit": .editingDidEndOnExit,
"allTouchEvents": .allTouchEvents,
"allEditingEvents": .allEditingEvents,
"allEvents": .allEvents,
]
private let controlStates: [String: UIControl.State] = [
"normal": .normal,
"highlighted": .highlighted,
"disabled": .disabled,
"selected": .selected,
"focused": .focused,
]
private var layoutActionsKey: UInt8 = 0
extension UIControl {
open override class var expressionTypes: [String: RuntimeType] {
var types = super.expressionTypes
types["contentVerticalAlignment"] = .uiControlContentVerticalAlignment
types["contentHorizontalAlignment"] = .uiControlContentHorizontalAlignment
for name in controlEvents.keys {
types[name] = .selector
}
#if arch(i386) || arch(x86_64)
// Private properties
for name in [
"adPrivacyData",
"requiresDisplayOnTracking",
] {
types[name] = nil
}
#endif
return types
}
open override func setValue(_ value: Any, forExpression name: String) throws {
if let action = value as? Selector, let event = controlEvents[name] {
var actions = objc_getAssociatedObject(self, &layoutActionsKey) as? NSMutableDictionary
if actions == nil {
actions = NSMutableDictionary()
objc_setAssociatedObject(self, &layoutActionsKey, actions, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
if let oldAction = actions?[name] as? Selector {
if oldAction == action {
return
}
removeTarget(nil, action: action, for: event)
}
actions?[name] = action
return
}
try super.setValue(value, forExpression: name)
}
func bindActions(for target: AnyObject) throws {
guard let actions = objc_getAssociatedObject(self, &layoutActionsKey) as? NSMutableDictionary else {
return
}
for (name, action) in actions {
guard let name = name as? String, let event = controlEvents[name], let action = action as? Selector else {
assertionFailure()
return
}
if let actions = self.actions(forTarget: target, forControlEvent: event), actions.contains("\(action)") {
// Already bound
} else {
if !target.responds(to: action) {
guard let responder = target as? UIResponder, let next = responder.next else {
throw LayoutError.message("Layout could find no suitable target for the \(action) action. If the method exists, it must be prefixed with @objc or @IBAction to be used with Layout")
}
try bindActions(for: next)
return
}
addTarget(target, action: action, for: event)
}
}
}
func unbindActions(for target: AnyObject) {
for action in actions(forTarget: target, forControlEvent: .allEvents) ?? [] {
removeTarget(target, action: Selector(action), for: .allEvents)
}
if let responder = target as? UIResponder, let next = responder.next {
unbindActions(for: next)
}
}
}
extension UIButton {
open override class func create(with node: LayoutNode) throws -> UIButton {
if let type = try node.value(forExpression: "type") as? UIButton.ButtonType {
return self.init(type: type)
}
return self.init(frame: .zero)
}
open override class var parameterTypes: [String: RuntimeType] {
return ["type": .uiButtonType]
}
open override class var expressionTypes: [String: RuntimeType] {
var types = super.expressionTypes
types["title"] = .string
types["attributedTitle"] = .nsAttributedString
types["titleColor"] = .uiColor
types["titleShadowColor"] = .uiColor
types["image"] = .uiImage
types["backgroundImage"] = .uiImage
for state in controlStates.keys {
types["\(state)Title"] = .string
types["\(state)AttributedTitle"] = .nsAttributedString
types["\(state)TitleColor"] = .uiColor
types["\(state)TitleShadowColor"] = .uiColor
types["\(state)Image"] = .uiImage
types["\(state)BackgroundImage"] = .uiImage
}
for (name, type) in UILabel.cachedExpressionTypes {
types["titleLabel.\(name)"] = type
}
for (name, type) in UIImageView.cachedExpressionTypes {
types["imageView.\(name)"] = type
}
// Private properties
types["lineBreakMode"] = nil
#if arch(i386) || arch(x86_64)
for name in [
"autosizesToFit",
"showPressFeedback",
] {
types[name] = nil
}
#endif
return types
}
open override func setValue(_ value: Any, forExpression name: String) throws {
switch name {
case "title": setTitle(value as? String, for: .normal)
case "titleColor": setTitleColor(value as? UIColor, for: .normal)
case "titleShadowColor": setTitleShadowColor(value as? UIColor, for: .normal)
case "image": setImage(value as? UIImage, for: .normal)
case "backgroundImage": setBackgroundImage(value as? UIImage, for: .normal)
case "attributedTitle": setAttributedTitle(value as? NSAttributedString, for: .normal)
default:
if let (prefix, state) = controlStates.first(where: { name.hasPrefix($0.key) }) {
switch name[prefix.endIndex ..< name.endIndex] {
case "Title": setTitle(value as? String, for: state)
case "TitleColor": setTitleColor(value as? UIColor, for: state)
case "TitleShadowColor": setTitleShadowColor(value as? UIColor, for: state)
case "Image": setImage(value as? UIImage, for: state)
case "BackgroundImage": setBackgroundImage(value as? UIImage, for: state)
case "AttributedTitle": setAttributedTitle(value as? NSAttributedString, for: state)
default:
break
}
return
}
try super.setValue(value, forExpression: name)
}
}
open override func value(forSymbol name: String) throws -> Any {
switch name {
case "title": return title(for: .normal) ?? ""
case "titleColor": return titleColor(for: .normal) as Any
case "titleShadowColor": return titleShadowColor(for: .normal) as Any
case "image": return image(for: .normal) as Any
case "backgroundImage": return backgroundImage(for: .normal) as Any
case "attributedTitle": return attributedTitle(for: .normal) as Any
default:
if let (prefix, state) = controlStates.first(where: { name.hasPrefix($0.key) }) {
switch name[prefix.endIndex ..< name.endIndex] {
case "Title": return title(for: state) as Any
case "TitleColor": return titleColor(for: state) as Any
case "TitleShadowColor": return titleShadowColor(for: state) as Any
case "Image": return image(for: state) as Any
case "BackgroundImage": return backgroundImage(for: state) as Any
case "AttributedTitle": return attributedTitle(for: state) as Any
default:
break
}
}
return try super.value(forSymbol: name)
}
}
}
private let textInputTraits: [String: RuntimeType] = [
"autocapitalizationType": .uiTextAutocapitalizationType,
"autocorrectionType": .uiTextAutocorrectionType,
"spellCheckingType": .uiTextSpellCheckingType,
"keyboardType": .uiKeyboardType,
"keyboardAppearance": .uiKeyboardAppearance,
"returnKeyType": .uiReturnKeyType,
"enablesReturnKeyAutomatically": .bool,
"isSecureTextEntry": .bool,
"smartQuotesType": .uiTextSmartQuotesType,
"smartDashesType": .uiTextSmartDashesType,
"smartInsertDeleteType": .uiTextSmartInsertDeleteType,
]
extension UILabel {
open override class var expressionTypes: [String: RuntimeType] {
var types = super.expressionTypes
types["textAlignment"] = .nsTextAlignment
types["lineBreakMode"] = .nsLineBreakMode
types["baselineAdjustment"] = .uiBaselineAdjustment
types["enablesMarqueeWhenAncestorFocused"] = .bool
#if arch(i386) || arch(x86_64)
// Private properties
for name in [
"adjustsLetterSpacingToFitWidth",
"autotrackTextToFit",
"centersHorizontally",
"color",
"drawsLetterpress",
"drawsUnderline",
"lineSpacing",
"marqueeEnabled",
"marqueeRunning",
"minimumFontSize",
"rawSize",
"rawSize.width",
"rawSize.height",
"shadowBlur",
] {
types[name] = nil
}
#endif
return types
}
open override func setValue(_ value: Any, forExpression name: String) throws {
if #available(iOS 12.0, *) {} else {
switch name {
case "enablesMarqueeWhenAncestorFocused":
return // does nothing
default:
break
}
}
try super.setValue(value, forExpression: name)
}
}
private let dragAndDropOptions: [String: RuntimeType] = [
"textDragDelegate": .uiTextDragDelegate,
"textDropDelegate": .uiTextDropDelegate,
"textDragOptions": .uiTextDragOptions,
]
extension UITextField {
open override class var expressionTypes: [String: RuntimeType] {
var types = super.expressionTypes
for (name, type) in textInputTraits {
types[name] = type
}
types["textAlignment"] = .nsTextAlignment
types["borderStyle"] = .uiTextBorderStyle
types["clearButtonMode"] = .uiTextFieldViewMode
types["leftViewMode"] = .uiTextFieldViewMode
types["rightViewMode"] = .uiTextFieldViewMode
types["minimumFontSize"] = .cgFloat
types["passwordRules"] = .uiTextInputPasswordRules
types["textContentType"] = .uiTextContentType
for (name, type) in dragAndDropOptions {
types[name] = type
}
#if arch(i386) || arch(x86_64)
// Private properties
for name in [
"animating",
"atomStyle",
"autoresizesTextToFit",
"becomesFirstResponderOnClearButtonTap",
"clearButtonOffset",
"clearButtonStyle",
"clearingBehavior",
"clearsPlaceholderOnBeginEditing",
"contentOffsetForSameViewDrops",
"continuousSpellCheckingEnabled",
"defaultTextAttributes",
"displaySecureEditsUsingPlainText",
"displaySecureTextUsingPlainText",
"drawsAsAtom",
"inactiveHasDimAppearance",
"isDevicePasscodeEntry",
"isUndoEnabled",
"labelOffset",
"nonEditingLinebreakMode",
"paddingBottom",
"paddingLeft",
"paddingRight",
"paddingTop",
"progress",
"recentsAccessoryView",
"selectionRange",
"shadowBlur",
"shadowColor",
"shadowOffset",
"textAutorresizesToFit",
"textCentersHorizontally",
"textCentersVertically",
"textSelectionBehavior",
] {
types[name] = nil
let name = "\(name)."
for key in types.keys where key.hasPrefix(name) {
types[key] = nil
}
}
#endif
return types
}
open override func setValue(_ value: Any, forExpression name: String) throws {
switch name {
case "autocapitalizationType": autocapitalizationType = value as! UITextAutocapitalizationType
case "autocorrectionType": autocorrectionType = value as! UITextAutocorrectionType
case "spellCheckingType": spellCheckingType = value as! UITextSpellCheckingType
case "keyboardType": keyboardType = value as! UIKeyboardType
case "keyboardAppearance": keyboardAppearance = value as! UIKeyboardAppearance
case "returnKeyType": returnKeyType = value as! UIReturnKeyType
case "enablesReturnKeyAutomatically": enablesReturnKeyAutomatically = value as! Bool
case "isSecureTextEntry": isSecureTextEntry = value as! Bool
case "passwordRules":
#if swift(>=4.1.5) || (!swift(>=4) && swift(>=3.4))
// TODO: warn about unavailability
if #available(iOS 12.0, *) {
passwordRules = value as? UITextInputPasswordRules
}
#endif
case "textContentType":
// TODO: warn about unavailability
if #available(iOS 10.0, *) {
textContentType = value as? UITextContentType
}
case "smartQuotesType":
// TODO: warn about unavailability
if #available(iOS 11.0, *) {
smartQuotesType = value as! UITextSmartQuotesType
}
case "smartDashesType":
// TODO: warn about unavailability
if #available(iOS 11.0, *) {
smartDashesType = value as! UITextSmartDashesType
}
case "smartInsertDeleteType":
// TODO: warn about unavailability
if #available(iOS 11.0, *) {
smartInsertDeleteType = value as! UITextSmartInsertDeleteType
}
case "textDragDelegate", "textDropDelegate", "textDragOptions":
// Does nothing on iOS 10 and earlier
if #available(iOS 11.0, *) {
fallthrough
}
default:
try super.setValue(value, forExpression: name)
}
}
}
extension UITextView {
open override class var expressionTypes: [String: RuntimeType] {
var types = super.expressionTypes
types["textAlignment"] = .nsTextAlignment
types["dataDetectorTypes"] = .uiDataDetectorTypes
for (name, type) in textInputTraits {
types[name] = type
}
for (name, type) in dragAndDropOptions {
types[name] = type
}
#if arch(i386) || arch(x86_64)
// Private properties
for name in [
"becomesEditableWithGestures",
"contentOffsetForSameViewDrops",
"continuousSpellCheckingEnabled",
"forceDisableDictation",
"forceEnableDictation",
"marginTop",
"shouldAutoscrollAboveBottom",
"shouldPresentSheetsInAWindowLayeredAboveTheKeyboard",
"tiledViewsDrawAsynchronously",
"usesTiledViews",
] {
types[name] = nil
let name = "\(name)."
for key in types.keys where key.hasPrefix(name) {
types[key] = nil
}
}
#endif
return types
}
open override func setValue(_ value: Any, forExpression name: String) throws {
switch name {
case "autocapitalizationType": autocapitalizationType = value as! UITextAutocapitalizationType
case "autocorrectionType": autocorrectionType = value as! UITextAutocorrectionType
case "spellCheckingType": spellCheckingType = value as! UITextSpellCheckingType
case "keyboardType": keyboardType = value as! UIKeyboardType
case "keyboardAppearance": keyboardAppearance = value as! UIKeyboardAppearance
case "returnKeyType": returnKeyType = value as! UIReturnKeyType
case "enablesReturnKeyAutomatically": enablesReturnKeyAutomatically = value as! Bool
case "isSecureTextEntry": isSecureTextEntry = value as! Bool
case "smartQuotesType":
// TODO: warn about unavailability
if #available(iOS 11.0, *) {
smartQuotesType = value as! UITextSmartQuotesType
}
case "smartDashesType":
// TODO: warn about unavailability
if #available(iOS 11.0, *) {
smartDashesType = value as! UITextSmartDashesType
}
case "smartInsertDeleteType":
// TODO: warn about unavailability
if #available(iOS 11.0, *) {
smartInsertDeleteType = value as! UITextSmartInsertDeleteType
}
case "textDragDelegate", "textDropDelegate", "textDragOptions":
// Does nothing on iOS 10 and earlier
if #available(iOS 11.0, *) {
fallthrough
}
default:
try super.setValue(value, forExpression: name)
}
}
}
extension UISearchBar {
open override class var expressionTypes: [String: RuntimeType] {
var types = super.expressionTypes
types["barPosition"] = .uiBarPosition
types["barStyle"] = .uiBarStyle
types["scopeButtonTitles"] = .array(of: .string)
types["searchBarStyle"] = .uiSearchBarStyle
for (name, type) in textInputTraits {
types[name] = type
}
#if arch(i386) || arch(x86_64)
// Private properties
for name in [
"centerPlaceholder",
"combinesLandscapeBars",
"contentInset",
"drawsBackground",
"drawsBackgroundInPalette",
"pretendsIsInBar",
"searchFieldLeftViewMode",
"searchTextPositionAdjustment",
"usesEmbeddedAppearance",
] {
types[name] = nil
let name = "\(name)."
for key in types.keys where key.hasPrefix(name) {
types[key] = nil
}
}
#endif
return types
}
open override func setValue(_ value: Any, forExpression name: String) throws {
switch name {
case "autocapitalizationType": autocapitalizationType = value as! UITextAutocapitalizationType
case "autocorrectionType": autocorrectionType = value as! UITextAutocorrectionType
case "spellCheckingType": spellCheckingType = value as! UITextSpellCheckingType
case "keyboardType": keyboardType = value as! UIKeyboardType
case "keyboardAppearance": keyboardAppearance = value as! UIKeyboardAppearance
case "returnKeyType": returnKeyType = value as! UIReturnKeyType
case "enablesReturnKeyAutomatically": enablesReturnKeyAutomatically = value as! Bool
case "isSecureTextEntry": isSecureTextEntry = value as! Bool
case "smartQuotesType":
// TODO: warn about unavailability
if #available(iOS 11.0, *) {
smartQuotesType = value as! UITextSmartQuotesType
}
case "smartDashesType":
// TODO: warn about unavailability
if #available(iOS 11.0, *) {
smartDashesType = value as! UITextSmartDashesType
}
case "smartInsertDeleteType":
// TODO: warn about unavailability
if #available(iOS 11.0, *) {
smartInsertDeleteType = value as! UITextSmartInsertDeleteType
}
default:
try super.setValue(value, forExpression: name)
}
}
}
#if swift(>=4.2)
private typealias Segment = UISegmentedControl.Segment
#else
private typealias Segment = UISegmentedControlSegment
#endif
private let controlSegments = RuntimeType.uiSegmentedControlSegment.values.mapValues { $0 as! Segment }
extension UISegmentedControl: TitleTextAttributes {
open override class func create(with node: LayoutNode) throws -> UISegmentedControl {
var items = [Any]()
for item in try node.value(forExpression: "items") as? [Any] ?? [] {
switch item {
case is String, is UIImage:
items.append(item)
default:
throw LayoutError("\(type(of: item)) is not a valid item type for \(classForCoder())", for: node)
}
}
return self.init(items: items)
}
open override class var expressionTypes: [String: RuntimeType] {
var types = super.expressionTypes
types["items"] = RuntimeType(NSArray.self)
// TODO: find a good naming scheme for left/right state variants
types["backgroundImage"] = .uiImage
types["titleColor"] = .uiColor
types["titleFont"] = .uiFont
for state in controlStates.keys {
types["\(state)BackgroundImage"] = .uiImage
types["\(state)TitleColor"] = .uiColor
types["\(state)TitleFont"] = .uiFont
}
types["dividerImage"] = .uiImage
types["contentPositionAdjustment"] = .uiOffset
types["contentPositionAdjustment.horizontal"] = .cgFloat
types["contentPositionAdjustment.vertical"] = .cgFloat
for segment in controlSegments.keys {
types["\(segment)ContentPositionAdjustment"] = .uiOffset
types["\(segment)ContentPositionAdjustment.horizontal"] = .cgFloat
types["\(segment)ContentPositionAdjustment.vertical"] = .cgFloat
}
#if arch(i386) || arch(x86_64)
// Private properties
for name in [
"aloneContentPositionAdjustment",
"alwaysNotifiesDelegateOfSegmentClicks",
"anyContentPositionAdjustment",
"axLongPressGestureRecognizer",
"barStyle",
"controlSize",
"removedSegment",
"segmentControlStyle",
"segmentedControlStyle",
"selectedSegment",
"transparentBackground",
] {
types[name] = nil
let name = "\(name)."
for key in types.keys where key.hasPrefix(name) {
types[key] = nil
}
}
#endif
return types
}
private func setItems(_ items: NSArray?, animated: Bool) throws {
let items = items ?? []
for (i, item) in items.enumerated() {
switch item {
case let title as String:
if i >= numberOfSegments {
insertSegment(withTitle: title, at: i, animated: animated)
} else {
if let oldTitle = titleForSegment(at: i), oldTitle == title {