Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute code when SecureField gets focused/unfocused in SwiftUI

I have a SecureField in SwiftUI. When this Field gets focused (when the user taps it) I want to manipulate a @State property for applying a offset modifier for the SecureField. When the SecureField gets out of focus the @State property should get reseted again. I want to do this for the SecureField to be visible if the keyboard gets toggled.

I achieved this with a TextField by using the onEditingChanged parameter of it, but this parameter doesn't exist for a SecureField.

How can I do this with a SecureField in SwiftUI?

This applies a offset if the TextField is focused:

import SwiftUI

let lightGreyColor = Color(red: 239.0/255.0, green: 243.0/255.0, blue: 244.0/255.0, opacity: 1.0)

struct ContentView : View {
    @State private var textFieldString: String = ""

    @State private var editingMode: Bool = false

    var body: some View {
        VStack {
            SecureField($textFieldString, placeholder: Text("My placeholder"))
            }
            .padding()
            .background(lightGreyColor)
            .cornerRadius(10.0)
            .padding()
            .offset(y: editingMode ? -150 : 0)
    }
}

But how to achieve the same with a SecureField in SwiftUI which doesn't have a onEditingChanged parameter?

struct ContentView : View {
    @State private var textFieldString: String = ""

    @State private var editingMode: Bool = false

    var body: some View {
        VStack {
            SecureField($textFieldString, placeholder: Text("My placeholder"))
            }
            .padding()
            .background(lightGreyColor)
            .cornerRadius(10.0)
            .padding()
            .offset(y: editingMode ? -150 : 0)
    }
}
like image 512
Andreas Schultz Avatar asked Jun 30 '19 13:06

Andreas Schultz


Video Answer


1 Answers

SwiftUI have no Method of focused/unfocused. You need to achieve this using @state and @observablle and onTapGesture. But onTapGesture call Every time when SecureField is taped.

SecureField($textFieldString, placeholder: Text("My placeholder"))
            }
.onTapGesture {
//here apply condition

}
like image 122
X Body Avatar answered Oct 18 '22 21:10

X Body