Here's a simple implementation of a secure text field that allows toggling between a secure and normal text view using SwiftUI only.
import SwiftUI
enum FocusedField { case normal, secure }
struct CustomSecureField: View {
@State var isSecure: Bool = true {
willSet {
if newValue {
focus = .secure
} else {
focus = .normal
}
}
}
@State var text: String = ""
@FocusState var focus: FocusedField?
var body: some View {
Group {
ZStack(alignment: .trailing) {
if isSecure {
SecureField("Password", text: $text)
.focused($focus, equals: .secure)
.animation(nil, value: isSecure)
} else {
TextField("Password", text: $text)
.focused($focus, equals: .normal)
.animation(nil, value: isSecure)
.textContentType(.password)
}
Image(systemName: isSecure ? "eye.slash" : "eye")
.animation(nil, value: isSecure)
.onTapGesture {
// This is necessary to prevent the keyboard from animating with a jump effect.
withAnimation {
isSecure.toggle()
}
}
}
}
.padding()
.background(
RoundedRectangle(cornerRadius: 12).fill(.gray.opacity(0.2))
)
.padding()
}
}
#Preview {
CustomSecureField()
}
You can try like this. I would suggest you go to ***SWIFT UI*** basics first
@State var email = ""
@State var password = ""
var body: some View {
Image("ISD-Logo")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 185, height: 140)
.clipped()
.padding(.bottom, 75)
VStack {
TextField("Email", text: $email)
.padding()
.background(Color(UIColor.lightGray))
.cornerRadius(5.0)
.padding(.bottom, 20)
SecureField("password", text: $password)
.padding()
.background(Color(UIColor.lightGray))
.cornerRadius(5.0)
.padding(.bottom, 20)
Button(action: { login() }) {
Text("Sign in")
.font(.headline)
.foregroundColor(.white)
.padding()
.frame(width: 220, height: 60)
.background(Color.black)
.cornerRadius(35.0)
}
}
.padding()
}
// Login and error message
func login() {
Auth.auth().signIn(withEmail: email, password: password) { (result, error) in
if error != nil {
self.isAlert = true
print(error?.localizedDescription ?? "")
} else {
print("success")
}
}
}
}
}
struct LoginView_Previews: PreviewProvider {
static var previews: some View {
LoginView()
}
}