-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCustomTextFieldDelegate.swift
99 lines (85 loc) · 2.91 KB
/
CustomTextFieldDelegate.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
//
// CustomTextFieldDelegate.swift
// Bourbon-iOS
//
// Created by Alyssa Torres on 5/5/17.
// Copyright © 2017 Ourglass. All rights reserved.
//
import UIKit
/// A custom text field delegate that handles editing and applies a common style.
class CustomTextFieldDelegate: NSObject {
var errorLabel: UILabel?
var isValid: (String?) -> Bool
var textField: UITextField
var inTableView: Bool
init(_ textField: UITextField,
isValid: @escaping (String?) -> Bool = defaultIsValid,
errorLabel: UILabel? = nil,
inTableView: Bool = false) {
self.errorLabel = errorLabel
self.isValid = isValid
self.textField = textField
self.inTableView = inTableView
super.init()
textField.delegate = self
applyTextFieldStyle()
applyErrorLabelStyle()
}
/// Applies a default style to the text field.
func applyTextFieldStyle() {
textField.useCustomBottomBorder()
textField.textColor = UIColor.white
textField.font = UIFont(name: Style.regularFont, size: 17.0)
}
/// Applies a default style to the error label.
func applyErrorLabelStyle() {
if let el = errorLabel {
el.isHidden = true
el.textColor = UIColor.red
el.font = UIFont(name: Style.lightFont, size: 11.0)
}
}
}
/// Default validity check on the field's text that checks that it is there
/// and not empty.
///
/// - Parameter text: the field's text
/// - Returns: `true` if valid, `false` if not
func defaultIsValid(_ text: String?) -> Bool {
if let t = text, t != "" {
return true
}
return false
}
extension CustomTextFieldDelegate: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
if let el = self.errorLabel {
el.isHidden = true
}
self.textField.changeBorderColor(UIColor.white)
}
func textFieldDidEndEditing(_ textField: UITextField) {
if self.isValid(self.textField.text) {
if let el = self.errorLabel {
el.isHidden = true
}
self.textField.changeBorderColor(UIColor.white)
} else {
if let el = self.errorLabel {
el.isHidden = false
}
self.textField.changeBorderColor(UIColor.red)
self.textField.shake()
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if self.inTableView, let nextField = textField.superview?.superview?.superview?.viewWithTag(textField.tag + 1) as? UITextField {
nextField.becomeFirstResponder()
} else if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField {
nextField.becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
return false
}
}