— SwiftUI, Text, User Interaction — 1 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.
A basic text view in SwiftUI is created using the Text
view:
1Text("Hello World")
By default, text in this view is not selectable.
From iOS 15.0+, macOS 12.0+, and Mac Catalyst 15.0+, SwiftUI provides the .textSelection
modifier to enable text selection.
Apply the .textSelection
modifier to your Text
view:
1Text("Selectable text")2 .textSelection(.enabled)
If you need to disable text selection for a specific Text
view, use:
1Text("Non selectable text")2 .textSelection(.disabled)
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` view5 Text("Non selectable text")6 .textSelection(.disabled)7}8.textSelection(.enabled)
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+.