How to Set isEditable and isSelectable for SwiftUI's TextEditor?

48 Views Asked by At

I am looking for equivalents to control the isEditable and isSelectable properties of NSTextView in SwiftUI's TextEditor.

In AppKit, I can easily make a text view editable or selectable using:

textView.isEditable = isEditable
textView.isSelectable = isSelectable

However, I'm having trouble finding how to achieve similar functionality with a TextEditor in SwiftUI.

1

There are 1 best solutions below

0
rob mayoff On

Preventing text selection

As of macOS Sonoma 14.3.1, TextEditor does not honor the textSelection or selectionDisabled modifiers. We need to resort to other means:

Preventing text editing

To prevent text editing, pass a Binding.constant to the TextEditor.

Demo

Use tab to move focus out of a TextField. Use ⌃tab (control-tab) to move focus out of a TextEditor.

import SwiftUI

struct MyView: View {
    @State var text = "hello world"

    var body: some View {
        Form {
            TextField("top", text: $text)

            LabeledContent("Editable") {
                TextEditor(text: $text)
            }

            LabeledContent("Selectable") {
                TextEditor(text: .constant(text))
            }

            LabeledContent("Unselectable") {
                TextEditor(text: $text)
                    .allowsHitTesting(false)
                    .focusable(false)
            }

            TextField("bottom", text: $text)
        }
    }
}

#Preview {
    MyView()
        .padding()
}