Womble Tristes
Womble Tristes

Reputation: 443

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)
    }
}

Upvotes: 11

Views: 3153

Answers (2)

Talha Sahi
Talha Sahi

Reputation: 19

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

}

Upvotes: 1

flannerykj
flannerykj

Reputation: 101

You could continue using the UITextField as before, and toggle its secureTextEntry field, instead of using the SecureField component.

Upvotes: 0

Related Questions