Get selected text from TextEditor performance issues
Closed this issue · 1 comments
liamcharger commented
Description
When using the code below, the selected text is received multiple seconds after selection. Is there a way to speed this up or a better way to achieve this result?
TextEditor(text: $text)
.introspect(.textEditor, on: .iOS(.v14, .v15, .v16, .v17, .v18)) { textEditor in
if let textRange = textEditor.selectedTextRange {
DispatchQueue.main.async {
let selectedText = textEditor.text(in: textRange) ?? ""
self.selectedText = selectedText
print(self.selectedText)
}
}
}
Checklist
- I have read the README before submitting this report.
- This issue hasn't been addressed in an existing GitHub issue or discussion.
Expected behavior
For the console to log the selected text as soon as it was selected.
Actual behavior
The print statement was executed multiple seconds (more than 5) after selection.
Steps to reproduce
Build and run a view with the following code:
TextEditor(text: $text)
.introspect(.textEditor, on: .iOS(.v14, .v15, .v16, .v17, .v18)) { textEditor in
if let textRange = textEditor.selectedTextRange {
DispatchQueue.main.async {
let selectedText = textEditor.text(in: textRange) ?? ""
self.selectedText = selectedText
print(self.selectedText)
}
}
}
Version information
1.2.0
Destination operating system
iOS 17
Xcode version information
16 beta 4
Swift Compiler version information
Apple Swift version 6.0 (swiftlang-6.0.0.6.8 clang-1600.0.23.1)
Target: arm64-apple-macosx15.0
liamcharger commented
I was able to fix the issue by assigning the value directly to a variable (inside a view model in my case), rather than initializing a new one and then assigning it like in the example.