kyle-n / HighlightedTextEditor

A SwiftUI view for dynamically highlighting user input
MIT License
719 stars 68 forks source link

Ambiguous use of 'onSelectionChange' #48

Closed Yang-Xijie closed 3 years ago

Yang-Xijie commented 3 years ago

Describe the bug

I want to create the editor App for macOS. But get the error Ambiguous use of 'onSelectionChange' in Xcode.

To Reproduce

Steps to reproduce the behavior:

  1. Go to Xcode, New Project -> macOS -> App
  2. Add this package using Swift Package Manager
  3. Paste below codes to ContentView.swift
  4. See error Ambiguous use of 'onSelectionChange' and cannot build the project.
import SwiftUI
import HighlightedTextEditor

struct ContentView: View {
    @State var text: String = "**bold** _italic_"

    var body: some View {
        VStack {
            HighlightedTextEditor(text: $text, highlightRules: .markdown)
                // optional modifiers
                .onCommit { print("commited") }
                .onEditingChanged { print("editing changed") }
                .onTextChange { print("latest text value", $0) }
                .onSelectionChange { print("NSRange of current selection", $0) } // FIXME
                .introspect { editor in
                    // access underlying UITextView or NSTextView
                    editor.textView.backgroundColor = .white
                }
        }
    }
}

Expected behavior I try that in iOS and it works just right. Printed out the NSRange when I make a selection.

Screenshots

image

Environment Please include:

Additional context English is not my native language; please excuse typing errors.

kyle-n commented 3 years ago

Apologies, this is bad documentation. Obviously you should be able to copy-paste sample code and the code should work.

Swift is telling you it cannot automatically infer which callback you mean, so you should type your callback function. Try this:

struct ContentView: View {
    @State var text: String = "**bold** _italic_"

    var body: some View {
        VStack {
            HighlightedTextEditor(text: $text, highlightRules: .markdown)
                .onSelectionChange { (range: NSRange) in // <--------------- NSRange
                    print(range)
                }
        }
    }
}

I'll update the documentation if this works for you.

kyle-n commented 3 years ago

@Yang-Xijie Can you try the code I've provided above? Want to know if this works.

Yang-Xijie commented 3 years ago

Sorry for replying late. It works! Thx a lot! 😃