Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Add Find and Replace to a TextEditor in SwiftUI
Written by Team Kodeco

When dealing with larger blocks of text in SwiftUI’s TextEditor, it can be useful to provide a user interface for find and replace operations. This feature allows users to search for specific strings of text and optionally replace them with others. In SwiftUI, this functionality is easily achievable with the findNavigator modifier.

Consider this example:

struct ContentView: View {
  @State private var text = "This is some editable text."
  @State private var isPresented = false

  var body: some View {
    NavigationStack {
      TextEditor(text: $text)
        .findNavigator(isPresented: $isPresented)
        .navigationTitle("Text Editor")
        .toolbar {
          Toggle(isOn: $isPresented) {
            Label("Find", systemImage: "magnifyingglass")
          }
        }
    }
  }
}

Tap the magnifying glass and search for “edit”. Your preview should look like this:

Find and replace interface in SwiftUI's TextEditor.
Find and replace interface in SwiftUI's TextEditor.

In this example, you create a TextEditor view, bind it to a @State variable text and attach a toolbar with a toggle button. The findNavigator modifier presents the search interface when isPresented is true and hides it when false. Tapping the magnifying glass in the toolbar toggles the visibility of the search interface.

Additionally, if you need to disable the find and replace operations in a TextEditor, you can use the .findDisabled(_:) and .replaceDisabled(_:) modifiers, respectively. Here’s how you can use these modifiers:

struct ContentView: View {
  @State private var text = "This is some editable text."
  @State private var isDisabled = true
  @State private var isPresented = false

  var body: some View {
    NavigationStack {
      TextEditor(text: $text)
        .findDisabled(isDisabled)
        .replaceDisabled(isDisabled)
        .findNavigator(isPresented: $isPresented)
        .navigationTitle("Text Editor")
        .toolbar {
          Toggle(isOn: $isPresented) {
            Label("Find", systemImage: "magnifyingglass")
          }
        }
    }
  }
}

Now tap the magnifying glass and your preview should look like:

Disabling find and replace in a SwiftUI TextEditor view.
Disabling find and replace in a SwiftUI TextEditor view.

Notice how the find and replace interface is disabled.

In this code snippet, you disable the find and replace operations in the TextEditor by setting isDisabled to true. The find and replace interface will not show up, even if isPresented is set to true, because the disabling modifiers findDisabled and replaceDisabled appear closer to the TextEditor.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.