When the user is entering the password, we need to use the ciphertext to display the content entered by the user, which requires the use of the SecureField view.
Knowledge points:
To use this view, first, add a property to the current struct. This property is used to store the password entered by the user, and a @State property proxy is added to the left of the property to bind the property to the interface element.
@State var password: String
Add a text view to display the password in real-time, just to demonstrate the use of the ciphertext input box for convenience. Since passwords are private, password information will not be displayed in the real situation.
Text("Your password is: \(password)")
Add a ciphertext input box and set the specified placeholder. Also, set the value of its text to the value of the password property, and bind it with the symbol "$" and the password property.
SecureField("Your password", text: $password) {
//
}
When the user completes the password input, in the trailing closure statement, print the password information entered by the user.
print("Your password is: \(password)")
Since we added a property to ContentView, we need to modify the code at the entry of the app.
Modify the initialization code of ContentView and set the initial value of the password property to empty.
@main
struct MySwiftUI2App: App {
var body: some Scene {
WindowGroup {
ContentView(password: "")
}
}
}
Again, the code for PreviewProvider needs to be modified.
Modify the initialization code of ContentView and set the initial value of the password property to empty.
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(password: "")
}
}
#endif
Set the border style of the input box to a rounded style.
.textFieldStyle(RoundedBorderTextFieldStyle())
Set the padding of the VStack to keep the SecureField a certain distance from the sides of the screen.
.padding()
Since SecureField is an interactive control, you need to click the Live Preview button here to activate the Live Preview feature. Only with the live preview feature, you can interact with the elements in the interface.
Click in the "Your password" input box to start password input.
TextField displays the characters entered by the user in plain text, while SecureField displays the characters as dots instead.
After code:
struct ContentView: View {
@State var password: String
var body: some View {
VStack {
Text("Your password is: \(password)")
SecureField("Your password", text: $password) {
print("Your password is: \(password)")
}
.textFieldStyle(RoundedBorderTextFieldStyle())
}
.padding()
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(password: "")
}
}
#endif
Visual effects:
Follow me on:
Commentaires