-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSTTextView.swift
More file actions
491 lines (432 loc) · 19.1 KB
/
Copy pathSTTextView.swift
File metadata and controls
491 lines (432 loc) · 19.1 KB
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
//
// STTextView.swift
// STBaseProject
//
// Created by 寒江孤影 on 2018/10/12.
//
import UIKit
public protocol STTextViewDelegate: NSObjectProtocol {
func st_textViewEditingChanged(textView: STTextView)
func st_textViewDidReachMaxTextCount(textView: STTextView, maxCount: Int)
func st_textViewTextCountDidChange(textView: STTextView, currentCount: Int, maxCount: Int)
func st_textViewWillChangeHeight(textView: STTextView, from oldHeight: CGFloat, to newHeight: CGFloat)
func st_textViewHeightDidChange(textView: STTextView, currentHeight: CGFloat, isReachMaxHeight: Bool)
func st_textViewDidChangeHeight(textView: STTextView, from oldHeight: CGFloat, to newHeight: CGFloat)
func st_textViewShouldChangeText(textView: STTextView, in range: NSRange, replacementText text: String) -> Bool
}
public extension STTextViewDelegate {
func st_textViewEditingChanged(textView: STTextView) {}
func st_textViewDidReachMaxTextCount(textView: STTextView, maxCount: Int) {}
func st_textViewTextCountDidChange(textView: STTextView, currentCount: Int, maxCount: Int) {}
func st_textViewWillChangeHeight(textView: STTextView, from oldHeight: CGFloat, to newHeight: CGFloat) {}
func st_textViewHeightDidChange(textView: STTextView, currentHeight: CGFloat, isReachMaxHeight: Bool) {}
func st_textViewDidChangeHeight(textView: STTextView, from oldHeight: CGFloat, to newHeight: CGFloat) {}
func st_textViewShouldChangeText(textView: STTextView, in range: NSRange, replacementText text: String) -> Bool { true }
}
public typealias STTextViewHeightChangeUserActionsBlock = (_ oldHeight: CGFloat, _ newHeight: CGFloat) -> Void
@IBDesignable
open class STTextView: STPlaceholderTextView {
open weak var cusDelegate: STTextViewDelegate?
open var shouldPreventResigningFirstResponder: (() -> Bool)?
open var shouldLimitTextCount: Bool = true
open private(set) var currentTextCount: Int = 0
open private(set) var currentInputHeight: CGFloat = 0
open private(set) var isReachMaxInputHeight: Bool = false
open var heightChangeUserActionsBlock: STTextViewHeightChangeUserActionsBlock?
private weak var heightConstraint: NSLayoutConstraint?
private var lastReportedHeight: CGFloat = 0
private var _minInputHeight: CGFloat = 0
@IBInspectable open var cornerRadius: CGFloat {
get { return self.layer.cornerRadius }
set {
self.layer.cornerRadius = newValue
self.st_updateLiquidGlassCornerRadius()
}
}
@IBInspectable open var clipsContentToBounds: Bool {
get { return self.layer.masksToBounds }
set { self.layer.masksToBounds = newValue }
}
@IBInspectable open var borderWidth: CGFloat {
get { return self.layer.borderWidth }
set { self.layer.borderWidth = newValue > 0 ? newValue : 0 }
}
@IBInspectable open var borderColor: UIColor {
get {
guard let color = self.layer.borderColor else { return .clear }
return UIColor(cgColor: color)
}
set { self.layer.borderColor = newValue.cgColor }
}
@IBInspectable open var animateHeightChange: Bool = true
@IBInspectable open var heightChangeAnimationDuration: Double = 0.35
@IBInspectable open var minimumNumberOfLines: Int = 1 {
didSet {
if self.minimumNumberOfLines < 1 {
self.minimumNumberOfLines = 1
}
if self.maximumNumberOfLines > 0, self.minimumNumberOfLines > self.maximumNumberOfLines {
self.minimumNumberOfLines = self.maximumNumberOfLines
}
self.updateHeightIfNeeded(notify: true, animated: false)
}
}
/// Set to 0 for unlimited height. Set to a positive value to enable scrolling after the given line count.
@IBInspectable open var maximumNumberOfLines: Int = 0 {
didSet {
if self.maximumNumberOfLines < 0 {
self.maximumNumberOfLines = 0
}
if self.maximumNumberOfLines > 0, self.maximumNumberOfLines < self.minimumNumberOfLines {
self.maximumNumberOfLines = self.minimumNumberOfLines
}
self.updateHeightIfNeeded(notify: true, animated: false)
}
}
open var numberOfLines: Int {
self.layoutManager.ensureLayout(for: self.textContainer)
var lineCount = 0
var index = 0
var lineRange = NSRange()
let numberOfGlyphs = self.layoutManager.numberOfGlyphs
while index < numberOfGlyphs {
_ = self.layoutManager.lineFragmentRect(forGlyphAt: index, effectiveRange: &lineRange)
index = NSMaxRange(lineRange)
lineCount += 1
}
return lineCount
}
open var maxTextHeight = CGFloat.greatestFiniteMagnitude {
didSet {
self.updateHeightIfNeeded(notify: true, animated: false)
}
}
@IBInspectable open var maxTextCount: Int = -1 {
didSet {
self.enforceTextCountIfNeeded()
self.notifyTextCount()
}
}
@IBInspectable public var minInputHeight: CGFloat {
get { return _minInputHeight }
set {
_minInputHeight = max(0, newValue)
self.updateHeightIfNeeded(notify: true, animated: false)
}
}
@IBInspectable public var maxInputHeight: CGFloat {
get { return self.maxTextHeight == CGFloat.greatestFiniteMagnitude ? 0 : self.maxTextHeight }
set {
self.maxTextHeight = newValue > 0 ? newValue : CGFloat.greatestFiniteMagnitude
}
}
override public var font: UIFont? {
didSet {
self.updateHeightIfNeeded(notify: true, animated: false)
}
}
override public var textColor: UIColor? {
didSet {
self.typingAttributes[.foregroundColor] = self.textColor ?? UIColor.label
}
}
override public var bounds: CGRect {
didSet {
if oldValue.size.width != self.bounds.size.width {
self.updateHeightIfNeeded(notify: true, animated: false)
}
}
}
override public var contentSize: CGSize {
didSet {
guard oldValue != self.contentSize else { return }
let animated = self.window != nil && self.isFirstResponder && self.animateHeightChange
self.updateHeightIfNeeded(notify: true, animated: animated)
}
}
override public var intrinsicContentSize: CGSize {
if self.heightConstraint != nil {
return CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric)
}
return CGSize(width: UIView.noIntrinsicMetric, height: self.calculatedHeight())
}
override public init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
self.config()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
self.config()
}
override open func layoutSubviews() {
super.layoutSubviews()
self.updateHeightConstraintIfNeeded()
}
override open func didMoveToSuperview() {
super.didMoveToSuperview()
self.updateHeightConstraintIfNeeded()
self.updateHeightIfNeeded(notify: false, animated: false)
}
@discardableResult
override open func resignFirstResponder() -> Bool {
if self.shouldPreventResigningFirstResponder?() == true {
return false
}
return super.resignFirstResponder()
}
override open func sizeThatFits(_ size: CGSize) -> CGSize {
let fittingHeight = self.fittingContentHeight(for: size.width)
let height = self.clampedHeight(for: fittingHeight)
return CGSize(width: size.width, height: height)
}
override open func sizeToFit() {
self.bounds.size.height = self.calculatedHeight()
}
override open func st_placeholderTextDidChange() {
self.handleTextChange()
}
override open func st_placeholderHeightAffectingChange() {
self.updateHeightIfNeeded(notify: true, animated: false)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
public func config(textLimitCount: Int) {
self.maxTextCount = textLimitCount
}
public func config(maxInputHeight: CGFloat) {
self.maxTextHeight = maxInputHeight > 0 ? maxInputHeight : CGFloat.greatestFiniteMagnitude
}
public func config(minimumNumberOfLines: Int, maximumNumberOfLines: Int) {
self.minimumNumberOfLines = minimumNumberOfLines
self.maximumNumberOfLines = maximumNumberOfLines
}
public func config(text: String?, textFont: UIFont? = nil, textColor: UIColor? = nil) {
if let textFont {
self.font = textFont
self.typingAttributes[.font] = textFont
}
if let textColor {
self.textColor = textColor
self.typingAttributes[.foregroundColor] = textColor
}
self.text = text
}
private func config() {
self.isScrollEnabled = false
self.delegate = self
self.keyboardDismissMode = .interactive
self.alwaysBounceVertical = false
self.typingAttributes[.font] = self.font ?? UIFont.st_systemFont(ofSize: 16)
self.typingAttributes[.foregroundColor] = self.textColor ?? UIColor.label
NotificationCenter.default.addObserver(
self,
selector: #selector(self.handleTextDidChangeNotification(_:)),
name: UITextView.textDidChangeNotification,
object: self
)
self.updateHeightConstraintIfNeeded()
self.updateHeightIfNeeded(notify: false, animated: false)
}
private func minTextHeight() -> CGFloat {
let lineBasedMin = self.heightForNumberOfLines(self.minimumNumberOfLines)
return _minInputHeight > 0 ? max(_minInputHeight, lineBasedMin) : lineBasedMin
}
private func maxTextHeightLimit() -> CGFloat {
let lineBasedMaxHeight = self.maximumNumberOfLines > 0
? self.heightForNumberOfLines(self.maximumNumberOfLines)
: CGFloat.greatestFiniteMagnitude
return min(self.maxTextHeight, lineBasedMaxHeight)
}
private func heightForNumberOfLines(_ numberOfLines: Int) -> CGFloat {
let font = self.typingAttributes[.font] as? UIFont ?? self.font ?? UIFont.st_systemFont(ofSize: 16)
var lineHeight = font.lineHeight
if let paragraphStyle = self.typingAttributes[.paragraphStyle] as? NSParagraphStyle {
if paragraphStyle.lineHeightMultiple > 0 {
lineHeight *= paragraphStyle.lineHeightMultiple
}
if paragraphStyle.minimumLineHeight > 0, lineHeight < paragraphStyle.minimumLineHeight {
lineHeight = paragraphStyle.minimumLineHeight
} else if paragraphStyle.maximumLineHeight > 0, lineHeight > paragraphStyle.maximumLineHeight {
lineHeight = paragraphStyle.maximumLineHeight
}
lineHeight += paragraphStyle.lineSpacing
}
return ceil(self.textContainerInset.top + self.textContainerInset.bottom + lineHeight * CGFloat(numberOfLines))
}
private func fittingContentHeight(for width: CGFloat) -> CGFloat {
let targetWidth = width > 0 ? width : UIScreen.main.bounds.width
let textViewFitting = super.sizeThatFits(
CGSize(width: targetWidth, height: CGFloat.greatestFiniteMagnitude)
).height
let placeholderHeight = self.placeholderFittingHeight(for: targetWidth)
guard (self.text ?? "").isEmpty, placeholderHeight > 0 else {
return textViewFitting
}
return max(textViewFitting, placeholderHeight)
}
private func clampedHeight(for fittingHeight: CGFloat) -> CGFloat {
return ceil(max(self.minTextHeight(), min(self.maxTextHeightLimit(), fittingHeight)))
}
private func calculatedHeight() -> CGFloat {
let targetWidth = self.bounds.width > 0 ? self.bounds.width : UIScreen.main.bounds.width
return self.clampedHeight(for: self.fittingContentHeight(for: targetWidth))
}
private func handleTextChange() {
self.enforceTextCountIfNeeded()
self.updateHeightIfNeeded(notify: true, animated: self.shouldAnimateHeightChangeNow())
self.notifyTextCount()
}
private func enforceTextCountIfNeeded() {
guard self.shouldLimitTextCount, self.maxTextCount > 0 else { return }
let value = self.text ?? ""
guard value.count > self.maxTextCount else { return }
self.text = String(value.prefix(self.maxTextCount))
self.cusDelegate?.st_textViewDidReachMaxTextCount(textView: self, maxCount: self.maxTextCount)
}
private func notifyTextCount() {
let currentCount = (self.text ?? "").count
self.currentTextCount = currentCount
guard self.maxTextCount > 0 else { return }
self.cusDelegate?.st_textViewTextCountDidChange(
textView: self,
currentCount: currentCount,
maxCount: self.maxTextCount
)
}
@objc private func handleTextDidChangeNotification(_ notification: Notification) {
self.updateHeightIfNeeded(notify: true, animated: self.shouldAnimateHeightChangeNow())
}
private func shouldAnimateHeightChangeNow() -> Bool {
return self.animateHeightChange && self.window != nil && self.isFirstResponder
}
private func updateHeightIfNeeded(notify: Bool, animated: Bool) {
self.invalidateIntrinsicContentSize()
self.updateHeightConstraintIfNeeded()
let targetWidth = self.bounds.width > 0 ? self.bounds.width : UIScreen.main.bounds.width
let fittingHeight = self.fittingContentHeight(for: targetWidth)
let currentHeight = self.clampedHeight(for: fittingHeight)
let maxHeightLimit = self.maxTextHeightLimit()
let isReachMaxHeight = fittingHeight >= maxHeightLimit && maxHeightLimit < CGFloat.greatestFiniteMagnitude
self.currentInputHeight = currentHeight
self.isReachMaxInputHeight = isReachMaxHeight
self.isScrollEnabled = isReachMaxHeight
let oldHeight = self.currentDisplayedHeight()
guard currentHeight != self.lastReportedHeight else {
if currentHeight != oldHeight {
self.setHeight(currentHeight)
}
if isReachMaxHeight {
self.scrollToVisibleCaretIfNeeded()
}
return
}
let applyHeightChange = {
self.setHeight(currentHeight)
self.heightChangeUserActionsBlock?(oldHeight, currentHeight)
self.superview?.layoutIfNeeded()
}
let completeHeightChange = {
self.layoutManager.ensureLayout(for: self.textContainer)
self.scrollToVisibleCaretIfNeeded()
self.lastReportedHeight = currentHeight
if notify {
self.cusDelegate?.st_textViewHeightDidChange(
textView: self,
currentHeight: currentHeight,
isReachMaxHeight: isReachMaxHeight
)
self.cusDelegate?.st_textViewDidChangeHeight(textView: self, from: oldHeight, to: currentHeight)
}
}
if notify {
self.cusDelegate?.st_textViewWillChangeHeight(textView: self, from: oldHeight, to: currentHeight)
}
if animated {
UIView.animate(
withDuration: self.heightChangeAnimationDuration,
delay: 0,
options: [.allowUserInteraction, .beginFromCurrentState],
animations: applyHeightChange,
completion: { _ in completeHeightChange() }
)
} else {
applyHeightChange()
completeHeightChange()
}
}
private func currentDisplayedHeight() -> CGFloat {
if let heightConstraint = self.heightConstraint {
return ceil(heightConstraint.constant)
}
if self.bounds.height > 0 {
return ceil(self.bounds.height)
}
return ceil(self.lastReportedHeight)
}
private func setHeight(_ height: CGFloat) {
if let heightConstraint = self.heightConstraint {
heightConstraint.constant = height
} else if !self.constraints.isEmpty || self.superview != nil {
self.invalidateIntrinsicContentSize()
self.setNeedsLayout()
} else {
self.frame.size.height = height
}
}
private func updateHeightConstraintIfNeeded() {
if self.heightConstraint?.isActive == true {
return
}
if let constraint = self.constraints.first(where: { self.isHeightConstraint($0) }) {
constraint.priority = UILayoutPriority(999)
self.heightConstraint = constraint
return
}
if let constraint = self.superview?.constraints.first(where: { self.isHeightConstraint($0) }) {
constraint.priority = UILayoutPriority(999)
self.heightConstraint = constraint
}
}
private func isHeightConstraint(_ constraint: NSLayoutConstraint) -> Bool {
guard constraint.firstAttribute == .height, constraint.relation == .equal else { return false }
return constraint.firstItem as? UIView === self || constraint.secondItem as? UIView === self
}
private func scrollToVisibleCaretIfNeeded() {
guard self.isReachMaxInputHeight, let textPosition = self.selectedTextRange?.end else { return }
let caretRect = self.caretRect(for: textPosition)
let insets = UIEdgeInsets(
top: self.contentInset.top + self.textContainerInset.top,
left: self.contentInset.left + self.textContainerInset.left + self.textContainer.lineFragmentPadding,
bottom: self.contentInset.bottom + self.textContainerInset.bottom,
right: self.contentInset.right + self.textContainerInset.right + self.textContainer.lineFragmentPadding
)
let visibleRect = self.bounds.inset(by: insets)
guard !visibleRect.contains(caretRect) else { return }
self.scrollRectToVisible(caretRect, animated: false)
}
}
extension STTextView: UITextViewDelegate {
public func textViewDidChange(_ textView: UITextView) {
self.handleTextChange()
self.cusDelegate?.st_textViewEditingChanged(textView: self)
}
public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if let cusDelegate, !cusDelegate.st_textViewShouldChangeText(textView: self, in: range, replacementText: text) {
return false
}
guard self.maxTextCount > 0, self.shouldLimitTextCount else { return true }
guard let currentText = textView.text else { return true }
guard let stringRange = Range(range, in: currentText) else { return true }
let markedRange = textView.markedTextRange
if markedRange != nil {
return true
}
let nextText = currentText.replacingCharacters(in: stringRange, with: text)
if nextText.count <= self.maxTextCount {
return true
}
self.cusDelegate?.st_textViewDidReachMaxTextCount(textView: self, maxCount: self.maxTextCount)
return false
}
}