Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI run function on losing focus TextField

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.

like image 364
SalsaJJ Avatar asked Mar 09 '26 10:03

SalsaJJ


1 Answers

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)
        })
            
    }
}
like image 199
jnpdx Avatar answered Mar 12 '26 03:03

jnpdx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!