-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathTextFieldCounter.swift
290 lines (227 loc) · 9.07 KB
/
TextFieldCounter.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
//
// TextFieldCounter.swift
// TextFieldCounter
//
// Created by Fabricio Serralvo on 12/7/16.
// Copyright © 2016 Fabricio Serralvo. All rights reserved.
//
import Foundation
import UIKit
// MARK: - TextFieldCounterDelegate
protocol TextFieldCounterDelegate: class {
func didReachMaxLength(textField: TextFieldCounter)
}
open class TextFieldCounter: UITextField, UITextFieldDelegate {
// MARK: - Properties
lazy internal var counterLabel: UILabel = UILabel()
weak var counterDelegate: TextFieldCounterDelegate?
// MARK: - IBInspectable: Limits and behaviors
@IBInspectable public dynamic var animate: Bool = true
@IBInspectable public dynamic var ascending: Bool = true
@IBInspectable public dynamic var counterColor: UIColor = .lightGray
@IBInspectable public dynamic var limitColor: UIColor = .red
@IBInspectable public var maxLength: Int = TextFieldCounter.defaultLength {
didSet {
if (isValidMaxLength(max: maxLength) == false) {
maxLength = TextFieldCounter.defaultLength
}
}
}
// MARK: - UITextFieldDelegate
private weak var _delegate: UITextFieldDelegate?
open override var delegate: UITextFieldDelegate? {
set {
self._delegate = newValue
}
get {
return self._delegate
}
}
// MARK: - Enumerations and Constants
enum AnimationType {
case basic
case didReachLimit
case unknown
}
static let defaultLength = 30
// MARK: - Init
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
super.delegate = self
counterLabel = createCounterLabel()
}
override open func draw(_ rect: CGRect) {
super.draw(rect)
rightView = counterLabel
rightViewMode = .whileEditing
}
// MARK: - Public Methods
///
/// Initializes a new beautiful *TextFieldCounter* programmatically.
///
/// - Parameters:
/// - frame: The frame of UITextField.
/// - limit: Defines the max lenght of UITextField. By default, if the number is not greater than 0, the limit will be `30`.
/// - animate: Indicates if counter label should animates when user reachs limit.
/// - ascending: Indicates if counter should be by ascending or descending way.
/// - counterColor: The color of label that displays the counter.
/// - limitColor: The color of label when user reachs limit.
public init(frame: CGRect,
limit: Int,
animate: Bool = true,
ascending: Bool = true,
counterColor: UIColor = .lightGray,
limitColor: UIColor = .red) {
super.init(frame: frame)
self.animate = animate
self.ascending = ascending
self.counterColor = counterColor
self.limitColor = limitColor
self.maxLength = self.calculateMaxLenght(withLimit: limit)
self.setupTextFieldStyle()
self.counterLabel = createCounterLabel()
super.delegate = self
}
// MARK: - Private Methods
private func calculateMaxLenght(withLimit limit: Int) -> Int {
if isValidMaxLength(max: limit) == false {
return TextFieldCounter.defaultLength
} else {
return limit
}
}
private func isValidMaxLength(max: Int) -> Bool {
return max > 0
}
// MARK: - Setup Methods
private func setupTextFieldStyle() {
self.backgroundColor = .white
self.layer.borderWidth = 0.35
self.layer.cornerRadius = 5.0
self.layer.borderColor = UIColor.lightGray.cgColor
}
private func createCounterLabel() -> UILabel {
let fontFrame = CGRect(x: 0, y: 0, width: calculateCounterLabelWidth(), height: Int(frame.height))
let label = UILabel(frame: fontFrame)
if let currentFont: UIFont = font {
label.font = currentFont
label.textColor = counterColor
label.textAlignment = label.userInterfaceLayoutDirection == .rightToLeft ? .right : .left
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 1
}
return label
}
private func localizedString(of number: Int) -> String {
return String.localizedStringWithFormat("%i", number)
}
private func calculateCounterLabelWidth() -> Int {
let biggestText = localizedString(of: maxLength)
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .left
paragraph.lineBreakMode = .byWordWrapping
var size = CGSize()
if let currentFont = font {
size = biggestText.size(withAttributes: [NSAttributedString.Key.font: currentFont,
NSAttributedString.Key.paragraphStyle: paragraph])
}
return Int(size.width) + 15
}
private func updateCounterLabel(count: Int) {
if count <= maxLength {
if (ascending) {
counterLabel.text = localizedString(of: count)
} else {
counterLabel.text = localizedString(of: maxLength - count)
}
}
prepareToAnimateCounterLabel(count: count)
}
private func textFieldCharactersCount(textField: UITextField, string: String, changeCharactersIn range: NSRange) -> Int {
var textFieldCharactersCount = 0
if let textFieldText = textField.text {
if !string.isEmpty {
textFieldCharactersCount = textFieldText.count + string.count - range.length
} else {
textFieldCharactersCount = textFieldText.count - range.length
}
}
return textFieldCharactersCount
}
private func callDidReachMaxLengthDelegateIfNeeded(count: Int) {
guard count >= maxLength else { return }
counterDelegate?.didReachMaxLength(textField: self)
}
// MARK: - Animations
private func prepareToAnimateCounterLabel(count: Int) {
var animationType: AnimationType = .unknown
if (count >= maxLength) {
animationType = .didReachLimit
} else if (count <= maxLength) {
animationType = .basic
}
animateTo(type: animationType)
}
private func animateTo(type: AnimationType) {
switch type {
case .basic:
animateCounterLabelColor(color: counterColor)
case .didReachLimit:
animateCounterLabelColor(color: limitColor)
fireHapticFeedback()
if (animate) {
counterLabel.shake(transform: CGAffineTransform(translationX: 5, y: 0), duration: 0.3)
}
default:
break
}
}
private func animateCounterLabelColor(color: UIColor) {
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: {
self.counterLabel.textColor = color
}, completion: nil)
}
// MARK: - Haptic Feedback
private func fireHapticFeedback() {
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.warning)
}
// MARK: - UITextFieldDelegate
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var shouldChange = false
let charactersCount = textFieldCharactersCount(textField: textField, string: string, changeCharactersIn: range)
if string.isEmpty {
shouldChange = true
} else {
shouldChange = charactersCount <= maxLength
}
updateCounterLabel(count: charactersCount)
callDidReachMaxLengthDelegateIfNeeded(count: charactersCount)
return shouldChange
}
// MARK: - UITextFieldDelegate Forwarding
public func textFieldDidBeginEditing(_ textField: UITextField) {
delegate?.textFieldDidBeginEditing?(self)
}
public func textFieldDidEndEditing(_ textField: UITextField) {
delegate?.textFieldDidEndEditing?(self)
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return delegate?.textFieldShouldReturn?(self) ?? true
}
public func textFieldShouldClear(_ textField: UITextField) -> Bool {
return delegate?.textFieldShouldClear?(self) ?? true
}
}
// MARK: - Private Extensions
private extension UIView {
func shake(transform: CGAffineTransform, duration: TimeInterval) {
self.transform = transform
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseInOut, animations: {
self.transform = CGAffineTransform.identity
}, completion: nil)
}
var userInterfaceLayoutDirection: UIUserInterfaceLayoutDirection {
return UIView.userInterfaceLayoutDirection(for: self.semanticContentAttribute)
}
}