-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathInputField.swift
1011 lines (818 loc) · 31 KB
/
InputField.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
//
// InputField.swift
//
// Made with ❤️ by Novum
//
// Copyright © Telefonica. All rights reserved.
//
import Foundation
import UIKit
public class InputField: UIView {
private typealias TextInputView = UIView & TextInput
enum Constants {
static let animationDuration: TimeInterval = 0.3
static let animationCurveControlPoint1 = CGPoint(x: 0.77, y: 0)
static let animationCurveControlPoint2 = CGPoint(x: 0.175, y: 1)
static let containerLayoutMargins = UIEdgeInsets(top: 8, left: 12, bottom: 8, right: 12)
static let bottomViewLayoutMargins = UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 12)
static let intrinsicContentWidth: CGFloat = 300
static let horizontalPlaceholderSpacing: CGFloat = 4
static let verticalPlaceholderHeightThreshold: CGFloat = 4
static let enabledAlpha: CGFloat = 1.0
static let disabledAlpha: CGFloat = 0.5
}
@frozen
public enum State {
case normal
case invalid
case disabled
}
@frozen
public enum SecureTextEntry {
case disabled
case enabled
}
@frozen
public struct StateStyle {
let placeholderTextColor: UIColor
let assistiveTextColor: UIColor
let textColor: UIColor
let editingPlaceholderTextColor: UIColor
}
@frozen
public enum TextInputStyle {
case textField
case textView
}
@frozen
public enum TextInputLimit: Equatable {
case infinite
case finite(characterCount: Int)
}
@frozen
public enum TextInputKeyboardStyle {
case keyboard(type: UIKeyboardType, textAutocorrectionType: UITextAutocorrectionType, textAutocapitalizationType: UITextAutocapitalizationType)
case picker
}
@frozen
public enum SideItem {
case image(UIImage)
case secureEntry
case picker
}
public struct Style {
let stateStyleByState: [State: StateStyle]
let secureTextEntry: SecureTextEntry
let textInputStyle: TextInputStyle
let textInputKeyboardStyle: TextInputKeyboardStyle
let leadingSideItem: SideItem?
let traillingSideItem: SideItem?
}
// MARK: Containers
private lazy var container: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [borderedView, bottomView])
stackView.alignment = .fill
stackView.distribution = .fill
stackView.axis = .vertical
return stackView
}()
private lazy var verticalTextInputStackView = UIStackView(arrangedSubviews: [backingPlaceholderLabel, horizontalTextInputStackView])
private lazy var horizontalTextInputStackView = UIStackView()
private lazy var borderedView: UIView = {
let view = UIView()
view.layer.borderWidth = 1
view.layer.borderColor = UIColor.border.cgColor
view.backgroundColor = .backgroundContainer
horizontalTextInputStackView.alignment = .fill
horizontalTextInputStackView.distribution = .fill
horizontalTextInputStackView.axis = .horizontal
horizontalTextInputStackView.spacing = 12
verticalTextInputStackView.alignment = .fill
verticalTextInputStackView.distribution = .fill
verticalTextInputStackView.axis = .vertical
verticalTextInputStackView.spacing = Constants.horizontalPlaceholderSpacing
let horizontalStackView = UIStackView(arrangedSubviews: [leadingButton, verticalTextInputStackView, traillingButton])
horizontalStackView.alignment = .center
horizontalStackView.distribution = .fill
horizontalStackView.axis = .horizontal
horizontalStackView.spacing = 10
horizontalStackView.isLayoutMarginsRelativeArrangement = true
horizontalStackView.layoutMargins = Constants.containerLayoutMargins
view.addSubview(withDefaultConstraints: horizontalStackView)
return view
}()
private lazy var horizontalAssistiveStackView = UIStackView(arrangedSubviews: [assistiveLabel, characterCountLabel])
private lazy var bottomView: UIView = {
let view = UIView()
view.layoutMargins = Constants.bottomViewLayoutMargins
horizontalAssistiveStackView.alignment = .top
horizontalAssistiveStackView.distribution = .fill
view.addSubview(constrainedToLayoutMarginsGuideOf: horizontalAssistiveStackView)
return view
}()
// MARK: Text
/// Dummy label (non visible). Used to adapt the space of the parent stackview to fit the `placeholderLayer`.
private lazy var backingPlaceholderLabel: UILabel = {
let label = UILabel()
label.textAlignment = .left
label.font = .textPreset1(weight: .regular)
label.numberOfLines = 1
label.alpha = 0
label.setContentCompressionResistancePriority(.required, for: .vertical)
label.setContentHuggingPriority(.fittingSizeLevel, for: .vertical)
label.isUserInteractionEnabled = false
return label
}()
private lazy var placeholderLayer: CATextLayer = {
let textLayer = CATextLayer()
textLayer.font = UIFont.textPreset3(weight: .regular)
textLayer.fontSize = UIFont.textPreset3(weight: .regular).pointSize
textLayer.contentsScale = UIScreen.main.scale
return textLayer
}()
private var textInputView: TextInputView!
private func textInputView(with style: TextInputStyle) -> TextInputView {
var textInputView: TextInputView
switch style {
case .textField:
textInputView = textField()
case .textView:
textInputView = textView()
}
textInputView.textAlignment = .left
textInputView.font = .textPreset3(weight: .regular)
textInputView.translatesAutoresizingMaskIntoConstraints = false
textInputView.setContentCompressionResistancePriority(.required, for: .vertical)
textInputView.setContentHuggingPriority(.fittingSizeLevel, for: .vertical)
textInputView.setContentCompressionResistancePriority(.init(rawValue: 1), for: .horizontal)
textInputView.setContentHuggingPriority(.init(rawValue: 1), for: .horizontal)
textInputView.backgroundColor = .backgroundContainer
return textInputView
}
private func textView() -> UITextView {
let textView = IntrinsicHeightTextView()
textView.delegate = self
textView.textContainerInset = .zero
textView.textContainer.lineFragmentPadding = 0
return textView
}
private func textField() -> UITextField {
let textField = UITextField()
textField.delegate = self
textField.addTarget(self, action: #selector(textDidChange), for: .editingChanged)
return textField
}
private lazy var prefixLabel: UILabel = {
let label = UILabel()
label.font = .textPreset3(weight: .regular)
label.numberOfLines = 1
label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
label.setContentHuggingPriority(.defaultLow, for: .horizontal)
label.textColor = .textSecondary
return label
}()
lazy var characterCountLabel: PaddingLabel = {
let label = PaddingLabel()
label.topInset = 4
label.textAlignment = .right
label.font = .textPreset1(weight: .regular)
label.numberOfLines = 2
label.setContentHuggingPriority(.required, for: .horizontal)
return label
}()
private lazy var assistiveLabel: PaddingLabel = {
let label = PaddingLabel()
label.topInset = 4
label.textAlignment = .left
label.font = .textPreset1(weight: .regular)
label.numberOfLines = 0
return label
}()
// MARK: Side items
private lazy var traillingButton: UIButton = {
let button = UIButton(type: .custom)
button.setContentHuggingPriority(.required, for: .horizontal)
button.addTarget(self, action: #selector(traillingButtonTapped), for: .touchUpInside)
return button
}()
private lazy var leadingButton: UIButton = {
let button = UIButton(type: .custom)
button.setContentHuggingPriority(.required, for: .horizontal)
button.addTarget(self, action: #selector(leadingButtonTapped), for: .touchUpInside)
return button
}()
// MARK: Properties
private var overridenAccessibilityLabel: String?
private var overridenAccessibilityValue: String?
private var overridenAccessibilityHint: String?
private var overridenAccessibilityTraits: UIAccessibilityTraits?
private lazy var animator = UIViewPropertyAnimator(
duration: Constants.animationDuration,
controlPoint1: Constants.animationCurveControlPoint1,
controlPoint2: Constants.animationCurveControlPoint2
)
@objc public var placeholderText: String? {
didSet {
backingPlaceholderLabel.text = placeholderText
placeholderLayer.string = placeholderText
}
}
@objc public var text: String? {
get { textInputView?.content }
set {
guard textInputView?.content != newValue else { return }
textInputView?.content = newValue
textDidChange()
}
}
@objc public var assistiveText: String? {
get { assistiveLabel.text }
set {
assistiveLabel.text = newValue
updateAssistiveLabelAlpha()
updateAssistiveLabelTextColor()
}
}
@objc public var prefixText: String? {
get { prefixLabel.text }
set {
prefixLabel.text = newValue
updatePrefixLabelAlpha()
}
}
public var textInputLimit: TextInputLimit = .infinite {
didSet {
updateCharacterCountLabel()
}
}
@objc public var borderColor: CGColor? {
get { borderedView.layer.borderColor }
set { borderedView.layer.borderColor = newValue }
}
@objc public var borderWidth: CGFloat {
get { borderedView.layer.borderWidth }
set { borderedView.layer.borderWidth = newValue }
}
@objc public var returnKeyType: UIReturnKeyType {
get { textInputView?.returnKeyType ?? .default }
set { textInputView?.returnKeyType = newValue }
}
public private(set) var state: State = .normal {
didSet {
guard state != oldValue else { return }
didUpdateState(previousState: oldValue)
}
}
public var style: Style {
didSet { updateStyle() }
}
public private(set) var isEditing = false
public var isOptional = false
public var automaticallyRemoveAssistiveTextOnTyping = true
public var validationStrategy: InputFieldValidationStrategy?
public var nonOptionalFieldFailureMessage: String?
public weak var delegate: InputFieldDelegate?
public weak var dataSource: InputFieldDataSource?
public init() {
style = .default
super.init(frame: .zero)
commonInit()
}
override public init(frame: CGRect) {
style = .default
super.init(frame: frame)
commonInit()
}
public required init?(coder: NSCoder) {
style = .default
super.init(coder: coder)
commonInit()
}
public init(style: Style = .default,
text: String? = nil,
placeholderText: String? = nil,
assistiveText: String? = nil,
nonOptionalFieldFailureMessage: String? = nil) {
self.style = style
super.init(frame: .zero)
self.text = text
self.placeholderText = placeholderText
self.assistiveText = assistiveText
self.nonOptionalFieldFailureMessage = nonOptionalFieldFailureMessage
commonInit()
}
private func commonInit() {
setUpView()
addBecomeFirstResponderTapGesture()
updatePrefixLabelAlpha()
updateCharacterCountLabel()
updatePlaceholderLayerPosition()
updatePlaceholderLayerTextColor()
updateAssistiveLabelTextColor()
updateAssistiveLabelAlpha()
updateStyle()
subscribeToPlaceholdeLabelBoundsChanges()
}
deinit {
unsubscribeToPlaceholdeLabelBoundsChanges()
}
override public func observeValue(forKeyPath _: String?, of _: Any?, change _: [NSKeyValueChangeKey: Any]?, context _: UnsafeMutableRawPointer?) {
updatePlaceholderLayerPosition()
updatePlaceholderLayerSize()
}
override public var intrinsicContentSize: CGSize {
let width = max(Constants.intrinsicContentWidth, container.intrinsicContentSize.width)
let height = container.intrinsicContentSize.height
return CGSize(width: width, height: height)
}
override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
guard traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle else { return }
borderColor = UIColor.border.cgColor
}
override public func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
borderedView.setMisticaRadius(.input)
}
}
// MARK: Validation
extension InputField: Validatable {
@objc public func validate() {
switch validationResult() {
case .success:
state = .normal
case .failure(let message):
show(errorText: message, animated: true)
}
}
@objc public func isValid() -> Bool {
validationResult() == .success
}
}
// MARK: Text input
public extension InputField {
override func endEditing(_ force: Bool) -> Bool {
textInputView?.endEditing(force) ?? super.endEditing(force)
}
@discardableResult
override func resignFirstResponder() -> Bool {
textInputView?.resignFirstResponder() ?? super.resignFirstResponder()
}
@discardableResult
override func becomeFirstResponder() -> Bool {
guard state != .disabled else { return false }
return textInputView?.becomeFirstResponder() ?? super.becomeFirstResponder()
}
override var canBecomeFirstResponder: Bool {
state != .disabled
}
override var isFirstResponder: Bool {
textInputView?.isFirstResponder ?? super.isFirstResponder
}
var beginningOfDocument: UITextPosition {
textInputView.beginningOfDocument
}
var endOfDocument: UITextPosition {
textInputView.endOfDocument
}
var isSecureTextEntry: Bool {
get { textInputView.isSecureTextEntry }
set { textInputView.isSecureTextEntry = newValue }
}
var selectedTextRange: UITextRange? {
get { textInputView.selectedTextRange }
set { textInputView.selectedTextRange = newValue }
}
func offset(from: UITextPosition, to toPosition: UITextPosition) -> Int {
textInputView.offset(from: from, to: toPosition)
}
func textRange(from: UITextPosition, to toPosition: UITextPosition) -> UITextRange? {
textInputView.textRange(from: from, to: toPosition)
}
func position(from position: UITextPosition, offset: Int) -> UITextPosition? {
textInputView.position(from: position, offset: offset)
}
}
// MARK: State
public extension InputField {
func set(state newState: State, animated: Bool) {
state = newState
startAnimations(animated: animated)
}
func show(assistiveText text: String?, animated: Bool) {
state = .normal
assistiveText = text
startAnimations(animated: animated)
}
func hideAssistiveText(animated: Bool) {
state = .normal
assistiveText = nil
startAnimations(animated: animated)
}
func show(errorText: String?, animated: Bool) {
state = .invalid
assistiveText = errorText
startAnimations(animated: animated)
}
func hideErrorText(animated: Bool) {
state = .normal
assistiveText = nil
startAnimations(animated: animated)
}
}
// MARK: Editing
private extension InputField {
func didBeginEditing() {
isEditing = true
addEditingAnimations()
startAnimations(animated: true)
delegate?.inputFieldDidBeginEditing(self)
}
func didEndEditing() {
isEditing = false
addEditingAnimations()
startAnimations(animated: true)
delegate?.inputFieldDidEndEditing(self)
}
@objc func textDidChange() {
updateCharacterCountLabel()
updatePrefixLabelAlpha()
updatePlaceholderLayerPosition()
if automaticallyRemoveAssistiveTextOnTyping && state == .invalid {
assistiveText = nil
state = .normal
startAnimations(animated: true)
}
delegate?.inputFieldTextDidChange(self)
}
func shouldBeginEditing() -> Bool {
delegate?.inputFieldShouldBeginEditing(self) ?? true
}
func shouldChangeCharactersIn(range: NSRange, replacementString string: String) -> Bool {
switch textInputLimit {
case .finite(let characterCount):
let text = self.text ?? ""
let newString = (text as NSString).replacingCharacters(in: range, with: string)
return newString.count <= characterCount
case .infinite:
return delegate?.inputField(self, shouldChangeCharactersIn: range, replacementString: string) ?? true
}
}
func shouldReturn() -> Bool {
delegate?.inputFieldShouldReturn(self) ?? true
}
}
// MARK: UITextViewDelegate
extension InputField: UITextViewDelegate {
public func textViewDidBeginEditing(_: UITextView) {
didBeginEditing()
}
public func textViewDidEndEditing(_: UITextView) {
didEndEditing()
}
public func textViewDidChange(_: UITextView) {
textDidChange()
}
public func textViewShouldBeginEditing(_: UITextView) -> Bool {
shouldBeginEditing()
}
public func textView(_: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
shouldChangeCharactersIn(range: range, replacementString: text)
}
}
// MARK: UITextFieldDelegate
extension InputField: UITextFieldDelegate {
public func textFieldDidBeginEditing(_: UITextField) {
didBeginEditing()
}
public func textFieldDidEndEditing(_: UITextField) {
didEndEditing()
}
public func textFieldShouldBeginEditing(_: UITextField) -> Bool {
shouldBeginEditing()
}
public func textField(_: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
shouldChangeCharactersIn(range: range, replacementString: string)
}
public func textFieldShouldReturn(_: UITextField) -> Bool {
shouldReturn()
}
}
// MARK: UIPickerViewDataSource
extension InputField: UIPickerViewDataSource {
public func numberOfComponents(in _: UIPickerView) -> Int {
1
}
public func pickerView(_: UIPickerView, numberOfRowsInComponent _: Int) -> Int {
dataSource?.inputFieldPickerElements(self).count ?? 0
}
}
// MARK: UIPickerViewDataSource
extension InputField: UIPickerViewDelegate {
public func pickerView(_: UIPickerView, titleForRow row: Int, forComponent _: Int) -> String? {
guard let elements = dataSource?.inputFieldPickerElements(self) else { return nil }
guard elements.indices.contains(row) else { return nil }
return elements[row]
}
public func pickerView(_: UIPickerView, didSelectRow row: Int, inComponent _: Int) {
guard let elements = dataSource?.inputFieldPickerElements(self) else { return }
guard elements.indices.contains(row) else { return }
text = elements[row]
dataSource?.inputField(self, didSelectPickerElementAt: row)
}
}
// MARK: Picker
extension InputField {
func pickerView() -> UIPickerView {
let pickerView = UIPickerView()
pickerView.delegate = self
pickerView.dataSource = self
pickerView.backgroundColor = .background
return pickerView
}
func pickerToolbar() -> UIToolbar {
let toolBar = UIToolbar()
toolBar.isTranslucent = true
toolBar.barStyle = .default
toolBar.backgroundColor = .background
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(resignFirstResponder))
let flexibleButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolBar.setItems([flexibleButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
toolBar.sizeToFit()
return toolBar
}
}
// MARK: Set up
private extension InputField {
func setUpView() {
isAccessibilityElement = true
layoutMargins = Constants.containerLayoutMargins
addSubview(container, constraints: [
leadingAnchor.constraint(equalTo: container.leadingAnchor),
trailingAnchor.constraint(equalTo: container.trailingAnchor),
topAnchor.constraint(equalTo: container.topAnchor),
bottomAnchor.constraint(greaterThanOrEqualTo: container.bottomAnchor)
])
verticalTextInputStackView.layer.addSublayer(placeholderLayer)
}
func addBecomeFirstResponderTapGesture() {
// Add a tap gesture to becomeFirstResponder whenever the user taps at any point of the container to improve user experience.
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(becomeFirstResponder))
tapGesture.numberOfTapsRequired = 1
borderedView.addGestureRecognizer(tapGesture)
}
func validationResult() -> InputFieldValidationResult {
if !isOptional && text.isEmpty {
return InputFieldValidationResult.failure(message: nonOptionalFieldFailureMessage ?? "")
} else {
return validationStrategy?.validate(text: text) ?? .success
}
}
func subscribeToPlaceholdeLabelBoundsChanges() {
backingPlaceholderLabel.addObserver(self, forKeyPath: #keyPath(UIView.bounds), options: .new, context: nil)
}
func unsubscribeToPlaceholdeLabelBoundsChanges() {
backingPlaceholderLabel.removeObserver(self, forKeyPath: #keyPath(UIView.bounds))
}
}
// MARK: Animations
private extension InputField {
var isPlaceholderFloating: Bool {
isEditing || !text.isEmpty
}
func addStateAnimations() {
animator.addAnimations {
self.updatePlaceholderLayerTextColor()
self.updateAssistiveLabelTextColor()
}
}
func addEditingAnimations() {
animator.addAnimations {
self.updatePlaceholderLayerPosition()
self.updatePlaceholderLayerTextColor()
self.updatePrefixLabelAlpha()
}
}
func updatePlaceholderLayerPosition() {
if isPlaceholderFloating {
placeholderLayer.frame.origin = .zero
placeholderLayer.fontSize = UIFont.textPreset1(weight: .regular).pointSize
} else {
let y = (backingPlaceholderLabel.bounds.height + Constants.horizontalPlaceholderSpacing) / 2
placeholderLayer.frame.origin = CGPoint(x: 0, y: y)
placeholderLayer.fontSize = UIFont.textPreset3(weight: .regular).pointSize
}
}
func updatePlaceholderLayerSize() {
let height = placeholderLayer.preferredFrameSize().height + Constants.verticalPlaceholderHeightThreshold
let width = backingPlaceholderLabel.bounds.width
placeholderLayer.frame.size = CGSize(width: width, height: height)
}
func updatePlaceholderLayerTextColor() {
if isEditing {
placeholderLayer.foregroundColor = stateStyle.editingPlaceholderTextColor.cgColor
} else {
placeholderLayer.foregroundColor = stateStyle.placeholderTextColor.cgColor
}
}
func updatePrefixLabelAlpha() {
prefixLabel.isHidden = prefixText.isEmpty
if isPlaceholderFloating {
prefixLabel.alpha = 1
} else {
prefixLabel.alpha = 0
}
}
func updateAssistiveLabelAlpha() {
let isHidden = assistiveText.isEmpty
assistiveLabel.isHidden = isHidden
if assistiveLabel.isHidden {
assistiveLabel.alpha = 0
} else {
assistiveLabel.alpha = 1
}
updateBottomViewVisibility()
delegate?.inputFieldShouldLayout(self)
}
func updateAssistiveLabelTextColor() {
assistiveLabel.textColor = stateStyle.assistiveTextColor
characterCountLabel.textColor = stateStyle.assistiveTextColor
}
func updateCharacterCountLabel() {
switch textInputLimit {
case .finite(let characterCount):
characterCountLabel.text = "\(text?.count ?? 0) / \(characterCount)"
characterCountLabel.isHidden = false
horizontalAssistiveStackView.axis = .horizontal
case .infinite:
characterCountLabel.text = ""
characterCountLabel.isHidden = true
horizontalAssistiveStackView.axis = .vertical
}
updateBottomViewVisibility()
}
func updateBottomViewVisibility() {
bottomView.isHidden = assistiveLabel.isHidden && characterCountLabel.isHidden
}
/// Starts animations from the animator. You may call this method every time the state is changed.
func startAnimations(animated: Bool) {
if animated {
animator.startAnimation()
} else {
UIView.performWithoutAnimation(animator.startAnimation)
}
}
}
// MARK: State
private extension InputField {
func didUpdateState(previousState _: State) {
addStateAnimations()
textInputView?.isEnabled = state != .disabled
textInputView?.textColor = stateStyle.textColor
textInputView.alpha = state == .disabled ? Constants.disabledAlpha : Constants.enabledAlpha
delegate?.inputFieldDidUpdateState(self)
}
}
// MARK: Side items
private extension InputField {
@objc func traillingButtonTapped(_ button: UIButton) {
switch style.traillingSideItem {
case .secureEntry:
textInputView?.isSecureTextEntry.toggle()
traillingButton.isSelected.toggle()
case .picker:
becomeFirstResponder()
case .image,
.none:
// Do nothing specific
break
}
delegate?.inputField(self, didTapTraillingButton: button)
}
@objc func leadingButtonTapped(_ button: UIButton) {
switch style.leadingSideItem {
case .secureEntry:
textInputView?.isSecureTextEntry.toggle()
traillingButton.isSelected.toggle()
case .picker:
becomeFirstResponder()
case .image,
.none:
// Do nothing specific
break
}
delegate?.inputField(self, didTapLeadingButton: button)
}
}
// MARK: Style
private extension InputField {
var stateStyle: StateStyle {
guard let stateStyle = style.stateStyleByState[state] else {
preconditionFailure("Style \(style) does not have stateStyle for state \(state). Check that the current style is defined properly.")
}
return stateStyle
}
func updateStyle() {
updateTextColorStyle()
updateSideItemsStyle()
updateTextInputStyle()
}
func updateTextInputStyle() {
let textInputView = self.textInputView(with: style.textInputStyle)
self.textInputView = textInputView
horizontalTextInputStackView.removeArrangedSubviews()
horizontalTextInputStackView.addArrangedSubview(prefixLabel)
horizontalTextInputStackView.addArrangedSubview(textInputView)
textInputView.isSecureTextEntry = style.secureTextEntry == .enabled
switch style.textInputKeyboardStyle {
case .picker:
textInputView.inputView = pickerView()
textInputView.inputAccessoryView = pickerToolbar()
textInputView.autocorrectionType = .no
textInputView.keyboardType = .default
textInputView.tintColor = .clear
case .keyboard(let keyboardType, let autocorrectionType, let autocapitalizationType):
textInputView.inputView = nil
textInputView.inputAccessoryView = nil
textInputView.autocorrectionType = autocorrectionType
textInputView.keyboardType = keyboardType
textInputView.autocapitalizationType = autocapitalizationType
textInputView.tintColor = .textActivated
}
}
func updateTextColorStyle() {
if isEditing {
placeholderLayer.foregroundColor = stateStyle.editingPlaceholderTextColor.cgColor
} else {
placeholderLayer.foregroundColor = stateStyle.placeholderTextColor.cgColor
}
textInputView?.textColor = stateStyle.textColor
assistiveLabel.textColor = stateStyle.assistiveTextColor
characterCountLabel.textColor = stateStyle.assistiveTextColor
}
func updateSideItemsStyle() {
updateLeadingSideItemStyle()
updateTraillingSideItemStyle()
}
func updateTraillingSideItemStyle() {
updateSideItemStyle(with: traillingButton, sideItem: style.traillingSideItem)
}
func updateLeadingSideItemStyle() {
updateSideItemStyle(with: leadingButton, sideItem: style.leadingSideItem)
}
func updateSideItemStyle(with button: UIButton, sideItem: SideItem?) {
switch sideItem {
case .secureEntry:
button.isHidden = false
button.setImage(.eyeEnabled, for: .selected)
button.setImage(.eyeDisabled, for: .normal)
case .picker:
button.isHidden = false
button.setImageForAllStates(.arrowDown)
case .image(let image):
button.isHidden = false
button.setImageForAllStates(image)
case .none:
button.isHidden = true
}
}
}
// MARK: Accessibility
public extension InputField {
override var accessibilityLabel: String? {
get { overridenAccessibilityLabel ?? placeholderText }
set { overridenAccessibilityLabel = newValue }
}
override var accessibilityValue: String? {
get { overridenAccessibilityValue ?? text }
set { overridenAccessibilityLabel = newValue }
}
override var accessibilityTraits: UIAccessibilityTraits {
get { overridenAccessibilityTraits ?? (state == .disabled ? .notEnabled : .none) }
set { overridenAccessibilityTraits = newValue }
}
override var accessibilityHint: String? {
get { overridenAccessibilityHint ?? assistiveText }
set { overridenAccessibilityHint = newValue }
}
var assistiveAccessibilityIdentifier: String? {
get { assistiveLabel.accessibilityIdentifier }
set { assistiveLabel.accessibilityIdentifier = newValue }
}
}
// MARK: Objc API
@objc public extension InputField {
func objc_setNormalState() {
state = .normal
}
func objc_setDisabledState() {