Reputation: 374
I want to run some function whenever a textfield loses focus. Textfield already has onEditingChange and onCommit but I want to run a validation function once the user leaves the textfield.
Something similar to what onblur does for web without cluttering any other view on screen.
Upvotes: 3
Views: 2884
Reputation: 52337
In iOS 15, @FocusState
and .focused
can give you this functionality. On iOS 13 and 14, you can use onEditingChanged
(shown in the second TextField
)
struct ContentView: View {
@State private var text = ""
@State private var text2 = ""
@FocusState private var isFocused: Bool
var body: some View {
TextField("Text goes here", text: $text)
.focused($isFocused)
.onChange(of: isFocused) { newValue in
if !newValue {
print("Lost focus")
}
}
TextField("Other text", text: $text2, onEditingChanged: { newValue in
print("Other text:",newValue)
})
}
}
Upvotes: 8