Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when a TextField loses the focus in SwiftUI for iOS?

Tags:

ios

swift

swiftui

TextField("Name", text: $name)

I found this method

func focusable(_ isFocusable: Bool = true, onFocusChange: @escaping (Bool) -> Void = { _ in }) -> some View

but it's only available for MacOS, How could I do something similar for iOS ?

like image 321
Sorin Lica Avatar asked Oct 16 '19 05:10

Sorin Lica


People also ask

How check TextField is empty or not in SwiftUI?

To check if the String value is empty I am going to use isEmpty that Swift provides. In the code example below I have two UITextFields which are called userNameTextField and userPasswordTextField. I first read the values that each UITextField contains and then check if these values are not empty.

How do I create a secure TextField in SwiftUI?

You just make a View with all the code you want for the SecureTextField and the TextField then all you have to do is call the HybridTextField where ever you need it. Nice!

How do you make a TextField first responder in SwiftUI?

You can create a custom text field and add a value to make it become first responder. Note: didBecomeFirstResponder is needed to make sure the text field becomes first responder only once, not on every refresh by SwiftUI !


1 Answers

You can use the initializer init(_:text:onEditingChanged:onCommit:) present in textfield. There you will be getting an action triggered when you begin editing and end editing. You can find out the minimal example below.

import SwiftUI

struct ContentView: View {
    @State private var greeting: String = "Hello world!"
    var body: some View {
        TextField("Welcome", text: $greeting, onEditingChanged: { (editingChanged) in
            if editingChanged {
                print("TextField focused")
            } else {
                print("TextField focus removed")
            }
        })
    }
}

Hope this helps.

like image 109
Subramanian Mariappan Avatar answered Sep 22 '22 05:09

Subramanian Mariappan