Swiftui How to let users select text ?

18 min read

In SwiftUI, you can enable text selection by using the textSelection modifier on a Text view.

Here's an example code snippet that demonstrates how to let users select text:

import SwiftUI

struct ContentView: View {
    @State private var isTextSelectable = false
    
    var body: some View {
        VStack {
            Text("Hello, World!")
                .textSelection($isTextSelectable)
                .padding()
            
            Button(action: {
                isTextSelectable.toggle()
            }) {
                Text(isTextSelectable ? "Disable Text Selection" : "Enable Text Selection")
                    .padding()
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

In this example, we create a Text view with the initial value of "Hello, World!". We use the textSelection modifier on the Text view and bind it to the isTextSelectable state variable.

To control the text selection, we add a Button below the Text view. When the button is tapped, it toggles the isTextSelectable state variable, which in turn enables or disables the text selection.

By default, text selection is disabled in SwiftUI, so you need to explicitly enable it using the textSelection modifier.