Enabling Text Selection for Non-Editable Text in SwiftUI

KD Knowledge Diet
2 min readDec 14, 2024

--

Text selection is a crucial feature in user interfaces, allowing users to interact with and manipulate text content. In SwiftUI, you can enable text selection for non-editable Text views using the `textSelection()` modifier. This modifier allows you to specify whether text selection should be enabled or disabled for Text views. In this guide, we’ll explore how to enable text selection for non-editable Text views in SwiftUI.

Enabling Text Selection for Individual Text Views:

To enable text selection for individual Text views in SwiftUI, you can use the `textSelection()` modifier and set it to `.enabled`. Here’s an example:

Text("Hello World!")
.textSelection(.enabled)

In this code, the Text view with the content “Hello World!” will be selectable, allowing users to tap and hold to initiate text selection.

Enabling Text Selection for a Hierarchy of Views:
You can also enable text selection for a hierarchy of views to affect all Text views within that hierarchy. Simply apply the `textSelection(.enabled)` modifier to the parent view. Here’s an example:

VStack {
Text("Text 1")
Text("Text 2")
}
.textSelection(.enabled)

In this case, both “Text 1” and “Text 2” within the VStack will be individually selectable.

Limitations on Text Selection:

It’s important to note that there are limitations to text selection in SwiftUI:

1. Individual Selection: Even when you set `textSelection(.enabled)` on a hierarchy of views, each Text view will still be selectable individually. There is no built-in way to select the contents of multiple Text views simultaneously.

2. macOS vs. iOS Behavior: On macOS, users can select a range of text using the mouse. On iOS, text selection is limited to selecting the entire contents of a Text view by long-pressing on it, which summons a system menu with context-appropriate actions such as Copy and Share.

Conclusion:

Enabling text selection for non-editable Text views in SwiftUI enhances the user experience and allows users to interact with text content. By using the `textSelection()` modifier with the `.enabled` option, you can enable text selection for individual Text views or entire hierarchies of views. However, keep in mind the limitations of text selection behavior between macOS and iOS platforms.

--

--

KD Knowledge Diet
KD Knowledge Diet

Written by KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!

No responses yet