TextSelection modifier in SwiftUI (iOS 15+)

Starting iOS 15 and SwiftUI 3, we can let the user select text from Text views. This is possible due to the newly introduced modifier called textSelection .

Use case for selection include copying information like error messages, IP addresses, phone numbers, or serial numbers so they can be pasted to another context.

textSelection modifier works on individual text views or containers to make each contained text view selectable. textSelection is backed by TextSelectability protocol.

Let’s start with an example.

struct DevTechieTextSelectionExample: View {
    var body: some View {
        Text("This text is selectable")
            .textSelection(.enabled)
    }
}

Note that textSelection modifier takes a parameter so we can choose between selection state being enabled or disabled.

struct DevTechieTextSelectionExample: View {
    var body: some View {
        VStack(spacing: 40) {
            Text("This text is selectable")
                .textSelection(.enabled)
            Text("This text is not selectable")
                .textSelection(.disabled)
        }
    }
}