siteline / swiftui-introspect

Introspect underlying UIKit/AppKit components from SwiftUI
MIT License
5.71k stars 352 forks source link

Get selected text from TextEditor performance issues #432

Closed liamcharger closed 2 months ago

liamcharger commented 2 months ago

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

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 2 months ago

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.