Contents

searchSelection(_:)

Binds the selection of the search field associated with the nearest searchable modifier to the given Textselection value.

Declaration

nonisolated func searchSelection(_ selection: Binding<TextSelection?>) -> some View

Parameters

  • selection:

    The selection value to bind.

Discussion

Use this modifier to read and set selection in your search interface. Selection is represented using TextSelection where the indices are relative to the search text you provide on the searchable(text:placement:prompt:) modifier. Note that this value will not represent selection outside of the text, such as in any leading tokens.

SwiftUI will automatically update this value when the user changes selection, such as by typing. Likewise, you can change selection by writing to this value.

The following example creates a search interface that selects all of the text on focus.

struct ContentView: View {
    @State var text = "Hello, world!"
    @State var selection: TextSelection?
    @FocusState var focused

    var body: some View {
        NavigationSplitView {
            Sidebar()
                .searchable(text: $text)
                .searchFocused($focused)
                .searchSelection($selection)
        } detail: {
            Detail()
        }
        .onChange(of: focused) {
            if focused {
                selection = TextSelection(
                    range: text.startIndex..<text.endIndex)
            }
        }
    }
}