简体   繁体   中英

How to detect when a TextField becomes active in SwiftUI?

.onTapGesture {
   // do something
}

Doesn't work because TextFields can be tapped without beginning editing mode.

Have you tried with onEditingChanged

    .onEditingChanged {
         //do something cool
    }

The answer is to initialize TextField with the onEditingChanged parameter.

We can then execute a closure conditionally depending upon whether the text field was edited or changes were committed:

TextField("", text: $email, onEditingChanged: { changed in
  if changed {
    // User began editing the text field
  }
  else {
    // User tapped the return key
  }
})

You Should try with it,

onEditingChanged: { (isBegin) in
                if isBegin {
                    print("Begins editing")
                } else {
                    print("Finishes editing")
                }
            },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM