@@ -72,7 +72,7 @@ open class GrowingTextView: UITextView {
7272 return CGSize ( width: UIViewNoIntrinsicMetric, height: 30 )
7373 }
7474
75- func associateConstraints( ) {
75+ private func associateConstraints( ) {
7676 // iterate through all text view's constraints and identify
7777 // height,from: https://github.com/legranddamien/MBAutoGrowingTextView
7878 for constraint in constraints {
@@ -94,7 +94,7 @@ open class GrowingTextView: UITextView {
9494 layoutIfNeeded ( )
9595 }
9696
97- private var isGrowing = false
97+ private var shouldScrollAfterHeightChanged = false
9898 override open func layoutSubviews( ) {
9999 super. layoutSubviews ( )
100100
@@ -118,26 +118,21 @@ open class GrowingTextView: UITextView {
118118 }
119119
120120 // Update height constraint if needed
121- let originHeight = heightConstraint? . constant ?? 0
122- if height != originHeight {
123- if height > originHeight { isGrowing = true }
121+ if height != heightConstraint!. constant {
122+ shouldScrollAfterHeightChanged = true
124123 heightConstraint!. constant = height
125- scrollToCorrectPosition ( )
126124 if let delegate = delegate as? GrowingTextViewDelegate {
127125 delegate. textViewDidChangeHeight ? ( self , height: height)
128126 }
127+ } else if shouldScrollAfterHeightChanged {
128+ shouldScrollAfterHeightChanged = false
129+ scrollToCorrectPosition ( )
129130 }
130131 }
131132
132133 private func scrollToCorrectPosition( ) {
133134 if self . isFirstResponder {
134- if self . isGrowing {
135- // Workaround to for incorrect scroll position on Swift4
136- self . heightConstraint!. constant += 0.0000001
137- self . isGrowing = false
138- } else {
139- self . scrollRangeToVisible ( NSMakeRange ( - 1 , 0 ) ) // Scroll to bottom
140- }
135+ self . scrollRangeToVisible ( NSMakeRange ( - 1 , 0 ) ) // Scroll to bottom
141136 } else {
142137 self . scrollRangeToVisible ( NSMakeRange ( 0 , 0 ) ) // Scroll to top
143138 }
@@ -188,16 +183,13 @@ open class GrowingTextView: UITextView {
188183
189184 // Limit the length of text
190185 @objc func textDidChange( notification: Notification ) {
191- if let notificationObject = notification. object as? GrowingTextView {
192- if notificationObject === self {
193- if maxLength > 0 && text. count > maxLength {
194-
195- let endIndex = text. index ( text. startIndex, offsetBy: maxLength)
196- text = String ( text [ ..< endIndex] )
197- undoManager? . removeAllActions ( )
198- }
199- setNeedsDisplay ( )
186+ if let sender = notification. object as? GrowingTextView , sender == self {
187+ if maxLength > 0 && text. count > maxLength {
188+ let endIndex = text. index ( text. startIndex, offsetBy: maxLength)
189+ text = String ( text [ ..< endIndex] )
190+ undoManager? . removeAllActions ( )
200191 }
192+ setNeedsDisplay ( )
201193 }
202194 }
203195}
0 commit comments