/
SkyFloatingLabelTextField.swift
608 lines (520 loc) · 18.7 KB
/
SkyFloatingLabelTextField.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
// Copyright 2016-2017 Skyscanner Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
// for the specific language governing permissions and limitations under the License.
import UIKit
/**
A beautiful and flexible textfield implementation with support for title label, error message and placeholder.
*/
@IBDesignable
open class SkyFloatingLabelTextField: UITextField { // swiftlint:disable:this type_body_length
/**
A Boolean value that determines if the language displayed is LTR.
Default value set automatically from the application language settings.
*/
open var isLTRLanguage: bool = UIApplication.shared.userInterfaceLayoutDirection == .leftToRight {
didSet {
updateTextAligment()
}
}
fileprivate func updateTextAligment() {
if isLTRLanguage {
textAlignment = .left
titleLabel.textAlignment = .left
} else {
textAlignment = .right
titleLabel.textAlignment = .right
}
}
// MARK: Animation timing
/// The value of the title appearing duration
dynamic open var titleFadeInDuration: TimeInterval = 0.2
/// The value of the title disappearing duration
dynamic open var titleFadeOutDuration: TimeInterval = 0.3
// MARK: Colors
fileprivate var cachedTextColor: UIColor?
/// A UIColor value that determines the text color of the editable text
@IBInspectable
override dynamic open var textColor: UIColor? {
set {
cachedTextColor = newValue
updateControl(false)
}
get {
return cachedTextColor
}
}
/// A UIColor value that determines text color of the placeholder label
@IBInspectable dynamic open var placeholderColor: UIColor = UIColor.lightGray {
didSet {
updatePlaceholder()
}
}
/// A UIColor value that determines text color of the placeholder label
dynamic open var placeholderFont: UIFont? {
didSet {
updatePlaceholder()
}
}
fileprivate func updatePlaceholder() {
if let placeholder = placeholder, let font = placeholderFont ?? font {
attributedPlaceholder = NSAttributedString(
string: placeholder,
attributes: [NSForegroundColorAttributeName: placeholderColor, NSFontAttributeName: font]
)
}
}
/// A UIColor value that determines the text color of the title label when in the normal state
@IBInspectable dynamic open var titleColor: UIColor = .gray {
didSet {
updateTitleColor()
}
}
/// A UIColor value that determines the color of the bottom line when in the normal state
@IBInspectable dynamic open var lineColor: UIColor = .lightGray {
didSet {
updateLineView()
}
}
/// A UIColor value that determines the color used for the title label and line when the error message is not `nil`
@IBInspectable dynamic open var errorColor: UIColor = .red {
didSet {
updateColors()
}
}
/// A UIColor value that determines the text color of the title label when editing
@IBInspectable dynamic open var selectedTitleColor: UIColor = .blue {
didSet {
updateTitleColor()
}
}
/// A UIColor value that determines the color of the line in a selected state
@IBInspectable dynamic open var selectedLineColor: UIColor = .black {
didSet {
updateLineView()
}
}
// MARK: Line height
/// A CGFloat value that determines the height for the bottom line when the control is in the normal state
@IBInspectable dynamic open var lineHeight: CGFloat = 0.5 {
didSet {
updateLineView()
setNeedsDisplay()
}
}
/// A CGFloat value that determines the height for the bottom line when the control is in a selected state
@IBInspectable dynamic open var selectedLineHeight: CGFloat = 1.0 {
didSet {
updateLineView()
setNeedsDisplay()
}
}
// MARK: View components
/// The internal `UIView` to display the line below the text input.
open var lineView: UIView!
/// The internal `UILabel` that displays the selected, deselected title or error message based on the current state.
open var titleLabel: UILabel!
// MARK: Properties
/**
The formatter used before displaying content in the title label.
This can be the `title`, `selectedTitle` or the `errorMessage`.
The default implementation converts the text to uppercase.
*/
open var titleFormatter: ((String) -> String) = { (text: String) -> String in
text.uppercased()
}
/**
Identifies whether the text object should hide the text being entered.
*/
override open var isSecureTextEntry: Bool {
set {
super.isSecureTextEntry = newValue
fixCaretPosition()
}
get {
return super.isSecureTextEntry
}
}
/// A String value for the error message to display.
open var errorMessage: String? {
didSet {
updateControl(true)
}
}
/// The backing property for the highlighted property
fileprivate var _highlighted: bool = false
/**
A Boolean value that determines whether the receiver is highlighted.
When changing this value, highlighting will be done with animation
*/
override open var isHighlighted: Bool {
get {
return _highlighted
}
set {
_highlighted = newValue
updateTitleColor()
updateLineView()
}
}
/// A Boolean value that determines whether the textfield is being edited or is selected.
open var editingOrSelected: Bool {
return super.isEditing || isSelected
}
/// A Boolean value that determines whether the receiver has an error message.
open var hasErrorMessage: Bool {
return errorMessage != nil && errorMessage != ""
}
fileprivate var _renderingInInterfaceBuilder: Bool = false
/// The text content of the textfield
@IBInspectable
override open var text: String? {
didSet {
updateControl(false)
}
}
/**
The String to display when the input field is empty.
The placeholder can also appear in the title label when both `title` `selectedTitle` and are `nil`.
*/
@IBInspectable
override open var placeholder: String? {
didSet {
setNeedsDisplay()
updatePlaceholder()
updateTitleLabel()
}
}
/// The String to display when the textfield is editing and the input is not empty.
@IBInspectable open var selectedTitle: String? {
didSet {
updateControl()
}
}
/// The String to display when the textfield is not editing and the input is not empty.
@IBInspectable open var title: String? {
didSet {
updateControl()
}
}
// Determines whether the field is selected. When selected, the title floats above the textbox.
open override var isSelected: Bool {
didSet {
updateControl(true)
}
}
// MARK: - Initializers
/**
Initializes the control
- parameter frame the frame of the control
*/
override public init(frame: CGRect) {
super.init(frame: frame)
init_SkyFloatingLabelTextField()
}
/**
Intialzies the control by deserializing it
- parameter coder the object to deserialize the control from
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
init_SkyFloatingLabelTextField()
}
fileprivate final func init_SkyFloatingLabelTextField() {
borderStyle = .none
createTitleLabel()
createLineView()
updateColors()
addEditingChangedObserver()
updateTextAligment()
}
fileprivate func addEditingChangedObserver() {
self.addTarget(self, action: #selector(SkyFloatingLabelTextField.editingChanged), for: .editingChanged)
}
/**
Invoked when the editing state of the textfield changes. Override to respond to this change.
*/
open func editingChanged() {
updateControl(true)
updateTitleLabel(true)
}
// MARK: create components
fileprivate func createTitleLabel() {
let titleLabel = UILabel()
titleLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight]
titleLabel.font = .systemFont(ofSize: 13)
titleLabel.alpha = 0.0
titleLabel.textColor = titleColor
addSubview(titleLabel)
self.titleLabel = titleLabel
}
fileprivate func createLineView() {
if lineView == nil {
let lineView = UIView()
lineView.isUserInteractionEnabled = false
self.lineView = lineView
configureDefaultLineHeight()
}
lineView.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
addSubview(lineView)
}
fileprivate func configureDefaultLineHeight() {
let onePixel: CGFloat = 1.0 / UIScreen.main.scale
lineHeight = 2.0 * onePixel
selectedLineHeight = 2.0 * self.lineHeight
}
// MARK: Responder handling
/**
Attempt the control to become the first responder
- returns: True when successfull becoming the first responder
*/
@discardableResult
override open func becomeFirstResponder() -> Bool {
let result = super.becomeFirstResponder()
updateControl(true)
return result
}
/**
Attempt the control to resign being the first responder
- returns: True when successfull resigning being the first responder
*/
@discardableResult
override open func resignFirstResponder() -> Bool {
let result = super.resignFirstResponder()
updateControl(true)
return result
}
// MARK: - View updates
fileprivate func updateControl(_ animated: Bool = false) {
updateColors()
updateLineView()
updateTitleLabel(animated)
}
fileprivate func updateLineView() {
if let lineView = lineView {
lineView.frame = lineViewRectForBounds(bounds, editing: editingOrSelected)
}
updateLineColor()
}
// MARK: - Color updates
/// Update the colors for the control. Override to customize colors.
open func updateColors() {
updateLineColor()
updateTitleColor()
updateTextColor()
}
fileprivate func updateLineColor() {
if hasErrorMessage {
lineView.backgroundColor = errorColor
} else {
lineView.backgroundColor = editingOrSelected ? selectedLineColor : lineColor
}
}
fileprivate func updateTitleColor() {
if hasErrorMessage {
titleLabel.textColor = errorColor
} else {
if editingOrSelected || isHighlighted {
titleLabel.textColor = selectedTitleColor
} else {
titleLabel.textColor = titleColor
}
}
}
fileprivate func updateTextColor() {
if hasErrorMessage {
super.textColor = errorColor
} else {
super.textColor = cachedTextColor
}
}
// MARK: - Title handling
fileprivate func updateTitleLabel(_ animated: Bool = false) {
var titleText: String?
if hasErrorMessage {
titleText = titleFormatter(errorMessage!)
} else {
if editingOrSelected {
titleText = selectedTitleOrTitlePlaceholder()
if titleText == nil {
titleText = titleOrPlaceholder()
}
} else {
titleText = titleOrPlaceholder()
}
}
titleLabel.text = titleText
updateTitleVisibility(animated)
}
fileprivate var _titleVisible: bool = false
/*
* Set this value to make the title visible
*/
open func setTitleVisible(
_ titleVisible: Bool,
animated: Bool = false,
animationCompletion: ((_ completed: Bool) -> Void)? = nil
) {
if _titleVisible == titleVisible {
return
}
_titleVisible = titleVisible
updateTitleColor()
updateTitleVisibility(animated, completion: animationCompletion)
}
/**
Returns whether the title is being displayed on the control.
- returns: True if the title is displayed on the control, false otherwise.
*/
open func isTitleVisible() -> Bool {
return hasText || hasErrorMessage || _titleVisible
}
fileprivate func updateTitleVisibility(_ animated: Bool = false, completion: ((_ completed: Bool) -> Void)? = nil) {
let alpha: CGFloat = isTitleVisible() ? 1.0 : 0.0
let frame: CGRect = titleLabelRectForBounds(bounds, editing: isTitleVisible())
let updateBlock = { () -> Void in
self.titleLabel.alpha = alpha
self.titleLabel.frame = frame
}
if animated {
let animationOptions: UIViewAnimationOptions = .curveEaseOut
let duration = isTitleVisible() ? titleFadeInDuration : titleFadeOutDuration
UIView.animate(withDuration: duration, delay: 0, options: animationOptions, animations: { () -> Void in
updateBlock()
}, completion: completion)
} else {
updateBlock()
completion?(true)
}
}
// MARK: - UITextField text/placeholder positioning overrides
/**
Calculate the rectangle for the textfield when it is not being edited
- parameter bounds: The current bounds of the field
- returns: The rectangle that the textfield should render in
*/
override open func textRect(forBounds bounds: CGRect) -> CGRect {
super.textRect(forBounds: bounds)
let rect = CGRect(
x: 0,
y: titleHeight(),
width: bounds.size.width,
height: bounds.size.height - titleHeight() - selectedLineHeight
)
return rect
}
/**
Calculate the rectangle for the textfield when it is being edited
- parameter bounds: The current bounds of the field
- returns: The rectangle that the textfield should render in
*/
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
let rect = CGRect(
x: 0,
y: titleHeight(),
width: bounds.size.width,
height: bounds.size.height - titleHeight() - selectedLineHeight
)
return rect
}
/**
Calculate the rectangle for the placeholder
- parameter bounds: The current bounds of the placeholder
- returns: The rectangle that the placeholder should render in
*/
override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
let rect = CGRect(
x: 0,
y: titleHeight(),
width: bounds.size.width,
height: bounds.size.height - titleHeight() - selectedLineHeight
)
return rect
}
// MARK: - Positioning Overrides
/**
Calculate the bounds for the title label. Override to create a custom size title field.
- parameter bounds: The current bounds of the title
- parameter editing: True if the control is selected or highlighted
- returns: The rectangle that the title label should render in
*/
open func titleLabelRectForBounds(_ bounds: CGRect, editing: Bool) -> CGRect {
if editing {
return CGRect(x: 0, y: 0, width: bounds.size.width, height: titleHeight())
}
return CGRect(x: 0, y: titleHeight(), width: bounds.size.width, height: titleHeight())
}
/**
Calculate the bounds for the bottom line of the control.
Override to create a custom size bottom line in the textbox.
- parameter bounds: The current bounds of the line
- parameter editing: True if the control is selected or highlighted
- returns: The rectangle that the line bar should render in
*/
open func lineViewRectForBounds(_ bounds: CGRect, editing: Bool) -> CGRect {
let height = editing ? selectedLineHeight : lineHeight
return CGRect(x: 0, y: bounds.size.height - height, width: bounds.size.width, height: height)
}
/**
Calculate the height of the title label.
-returns: the calculated height of the title label. Override to size the title with a different height
*/
open func titleHeight() -> CGFloat {
if let titleLabel = titleLabel,
let font = titleLabel.font {
return font.lineHeight
}
return 15.0
}
/**
Calcualte the height of the textfield.
-returns: the calculated height of the textfield. Override to size the textfield with a different height
*/
open func textHeight() -> CGFloat {
return self.font!.lineHeight + 7.0
}
// MARK: - Layout
/// Invoked when the interface builder renders the control
override open func prepareForInterfaceBuilder() {
if #available(iOS 8.0, *) {
super.prepareForInterfaceBuilder()
}
borderStyle = .none
isSelected = true
_renderingInInterfaceBuilder = true
updateControl(false)
invalidateIntrinsicContentSize()
}
/// Invoked by layoutIfNeeded automatically
override open func layoutSubviews() {
super.layoutSubviews()
titleLabel.frame = titleLabelRectForBounds(bounds, editing: isTitleVisible() || _renderingInInterfaceBuilder)
lineView.frame = lineViewRectForBounds(bounds, editing: editingOrSelected || _renderingInInterfaceBuilder)
}
/**
Calculate the content size for auto layout
- returns: the content size to be used for auto layout
*/
override open var intrinsicContentSize: CGSize {
return CGSize(width: bounds.size.width, height: titleHeight() + textHeight())
}
// MARK: - Helpers
fileprivate func titleOrPlaceholder() -> String? {
guard let title = title ?? placeholder else {
return nil
}
return titleFormatter(title)
}
fileprivate func selectedTitleOrTitlePlaceholder() -> String? {
guard let title = selectedTitle ?? title ?? placeholder else {
return nil
}
return titleFormatter(title)
}
} // swiftlint:disable:this file_length