SecureField trong SwiftUI
1. Cơ bản
@State private var password = ""
SecureField("Password", text: $password)
.textFieldStyle(.roundedBorder)2. Show/Hide Password
struct PasswordField: View {
@State private var password = ""
@State private var showPassword = false
var body: some View {
HStack {
if showPassword {
TextField("Password", text: $password)
} else {
SecureField("Password", text: $password)
}
Button {
showPassword.toggle()
} label: {
Image(systemName: showPassword ? "eye.slash" : "eye")
.foregroundColor(.gray)
}
}
.textFieldStyle(.roundedBorder)
}
}3. Trong Login Form
struct LoginView: View {
@State private var email = ""
@State private var password = ""
var body: some View {
VStack(spacing: 16) {
TextField("Email", text: $email)
.keyboardType(.emailAddress)
.autocapitalization(.none)
SecureField("Password", text: $password)
Button("Login") {
// Login action
}
.disabled(email.isEmpty || password.isEmpty)
}
.textFieldStyle(.roundedBorder)
.padding()
}
}📝 Tips
- SecureField luôn hiện dots
- Dùng pattern show/hide để toggle
.textContentType(.password)cho AutoFill
Last updated on