WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

How to let users select text

Paul Hudson    @twostraws   

Updated for Xcode 14.2

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

The line “You can't touch this” above the line “Break it down!”. A selection menu hovers over the second line.

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

The line “You can't touch this” above the line “Break it down!”. A selection menu hovers over the first line.

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

A list consisting of rows of text. The first row has a selection menu hovering beneath it.

Tip: You need to press and hold directly on the text in a row rather than anywhere else.

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 3.9/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.