Skip to content
DeveloperMemos

Enabling Text Selection in SwiftUI Text Labels

SwiftUI, Text, User Interaction1 min read

SwiftUI provides a simple and intuitive way to create user interfaces. However, enabling text selection in Text views isn't straightforward. This article will guide you on how to allow users to select text in SwiftUI text labels.

Basic Text View

A basic text view in SwiftUI is created using the Text view:

1Text("Hello World")

By default, text in this view is not selectable.

Enabling Text Selection

From iOS 15.0+, macOS 12.0+, and Mac Catalyst 15.0+, SwiftUI provides the .textSelection modifier to enable text selection.

Step 1: Adding the Text Selection Modifier

Apply the .textSelection modifier to your Text view:

1Text("Selectable text")
2 .textSelection(.enabled)

Step 2: Disabling Text Selection

If you need to disable text selection for a specific Text view, use:

1Text("Non selectable text")
2 .textSelection(.disabled)

Step 3: Applying to a Container

You can also apply textSelection to a container, enabling text selection for all Text views inside it:

1VStack {
2 Text("Selectable text1")
3 Text("Selectable text2")
4 // Disable selection only for this `Text` view
5 Text("Non selectable text")
6 .textSelection(.disabled)
7}
8.textSelection(.enabled)

Conclusion

Enabling text selection in SwiftUI Text views is easily achievable with the .textSelection modifier. This feature enhances the user experience by allowing users to interact with text content in your SwiftUI applications.

Remember, this feature requires iOS 15.0+, macOS 12.0+, or Mac Catalyst 15.0+.