TextEditor disable editing

Viewed 1266

Overview:

  • I have a TextEditor that uses a binding to a constant, so that value can't change.

Aim:

  • I would like the text editor not to show the keyboard however still allow the user to copy text.

Question:

  • How to achieve copying of text but without showing the keyboard?
  • I would prefer to do in SwiftUI or is it only possible using UIViewRepresentable?

Code:

import SwiftUI

struct TextView: View {
    
    let text: String
    
    var body: some View {
        TextEditor(text: .constant(text))
    }
}

struct TextView_Previews: PreviewProvider {
    static var previews: some View {
        
        let text = "this is some text"
        
        TextView(text: text)
    }
}
2 Answers

iOS 15

yourField
  .textSelection(.enabled)

iOS 14 and Lower

I don't think there's great swiftui support for this right now, considering it's a constant, I might just manually add the copy behavior:

struct CopyableLabel : View {
    let text: String = "here's a constant"

    var body: some View {
        Text(text)
            .contextMenu {
                Button(action: {
                    UIPasteboard.general.string = text
                }) {
                    Text("Copy")
                }
            }
    }
}

If you want the user to be able to manually select portions, I think the most efficient way would be to drop to uikit, or roll something more complex

A better way is using "textSelection" modifly

Text("Hello, world!")
    .textSelection(.enabled)
    .padding()
Related