Updated for Xcode 13.3
New in iOS 15
Swift’s Text
views represent static, unselectable text by default, but you can change that using the .textSelection()
modifier with the .enabled
value.
For example, this makes some text the user can select, and some the user cannot:
VStack(spacing: 50) {
Text("You can't touch this")
Text("Break it down!")
.textSelection(.enabled)
}
Download this as an Xcode project
When text is selected, the user automatically gains access to the regular text actions such as Copy and Share. However, right now at least the whole text area is copied – you don’t get a text selection loupe, so you can’t select just a few words.
Setting textSelection()
on any kind of group of views will automatically make all text inside that group selectable. For example, we could make both text views in our previous example selectable by moving the modifier up to the stack:
VStack(spacing: 50) {
Text("You can't touch this")
Text("Break it down!")
}
.textSelection(.enabled)
Download this as an Xcode project
You can even apply textSelection()
to a list, in which case the text rows in the list become selectable:
List(0..<100) { index in
Text("Row \(index)")
}
.textSelection(.enabled)
Download this as an Xcode project
Tip: You need to press and hold directly on the text in a row rather than anywhere else.
SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.