1
  • My code: I use onCommit closure to be able to perform an action by pressing the Enter key when the TextField is being focused.
import SwiftUI

struct ContentView: View {
  @State private var text = ""

  var body: some View {
    TabView {
      TextField(
        "",
        text: $text,
        onCommit: { print("onCommit") } // I have a problem here
      )
        .tabItem {
          Text("Tab 1")
        }

      Text("Tab 2")
        .tabItem {
          Text("Tab 2")
        }

      Text("Tab 3")
        .tabItem {
          Text("Tab 3")
        }
    }
  }
}
  • My problem: The onCommit closure is also always triggered when I switch to another tab, making my App perform an unexpected action.
  • My questions:
    1. This is the bug or the feature?
    2. Is there a way to avoid the onCommit trigger every time I switch to another tab?
Thai D. V.
  • 483
  • 1
  • 5
  • 11

2 Answers2

1

Deprecated

Use init(_:text:prompt:) instead. Add the onSubmit(of:_:) view modifier for the onCommit behavior, and onFocus(_:) for the onEditingChanged behavior.

import SwiftUI

struct ContentView: View {
  @State private var text = ""

  var body: some View {
    TabView {
      TextField("", text: $text)
        .onSubmit {               // new api
          print("onCommit")
        }
        .tabItem {
          Text("Tab 1")
        }

      Text("Tab 2")
        .tabItem {
          Text("Tab 2")
        }

      Text("Tab 3")
        .tabItem {
          Text("Tab 3")
        }
    }
  }
}
  • onSubmit doesn't trigger every time I switch to another tab.
Thai D. V.
  • 483
  • 1
  • 5
  • 11
0

onCommit

An action to perform when the user performs an action (for example, when the user presses the Return key) while the text field has focus. https://developer.apple.com

It is by design. When you change tab, the TextField loses focus. Therefore, onCommit is called.

onCommit is also called when the user presses the Return key.

mahan
  • 12,366
  • 5
  • 48
  • 83