Skip to content

Commit c7eccad

Browse files
nuno-vieirapolqf
andcommitted
Fix input text view not scrolling to caret position after pasting text (#2649)
* Fix input text view not scrolling to caret position after pasting text * Update Sources/StreamChatUI/CommonViews/InputTextView/InputTextView.swift Co-authored-by: Pol Quintana <[email protected]> * Move textChangedFromClipboard before super --------- Co-authored-by: Pol Quintana <[email protected]>
1 parent 9d76ad5 commit c7eccad

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

Sources/StreamChatUI/CommonViews/InputTextView/InputTextView.swift

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@ open class InputTextView: UITextView, AppearanceProvider {
3030
.withBidirectionalLanguagesSupport
3131
.withAdjustingFontForContentSizeCategory
3232

33+
/// A boolean value to control whether the text was changed by pasting a text from the clipboard.
34+
private var textChangedFromClipboard = false
35+
3336
override open var text: String! {
3437
didSet {
3538
textDidChangeProgrammatically()
@@ -127,6 +130,13 @@ open class InputTextView: UITextView, AppearanceProvider {
127130
@objc open func handleTextChange() {
128131
placeholderLabel.isHidden = !text.isEmpty
129132
setTextViewHeight()
133+
134+
// If the user pasted text from the clipboard, we want to scroll to the caret position.
135+
if textChangedFromClipboard, let selectedTextRange = self.selectedTextRange {
136+
let caret = caretRect(for: selectedTextRange.start)
137+
scrollRectToVisible(caret, animated: true)
138+
textChangedFromClipboard = false
139+
}
130140
}
131141

132142
open func setTextViewHeight() {
@@ -167,18 +177,14 @@ open class InputTextView: UITextView, AppearanceProvider {
167177
if let pasteboardImage = UIPasteboard.general.image {
168178
clipboardAttachmentDelegate?.inputTextView(self, didPasteImage: pasteboardImage)
169179
} else {
180+
if UIPasteboard.general.string != nil {
181+
textChangedFromClipboard = true
182+
}
183+
170184
super.paste(sender)
171185
// On text paste, textView height will not change automatically
172186
// so we must call this function
173187
setTextViewHeight()
174188
}
175-
176-
// When pasting text, we should scroll to the bottom, so that if the text
177-
// is very long, it correctly scrolls to the input caret.
178-
if let pasteboardText = UIPasteboard.general.string {
179-
let padding = directionalLayoutMargins.leading
180-
let bottomOffset = contentSize.height - padding
181-
setContentOffset(.init(x: 0, y: contentSize.height - padding), animated: true)
182-
}
183189
}
184190
}

0 commit comments

Comments
 (0)