Answers for "Creating Shake Fail Feedback Using Animation"

0

Creating Shake Fail Feedback Using Animation

struct ContentView: View {
    @State var offset:CGFloat = 0
    @State private var username: String = ""
    @State private var password: String = ""
    
    var body: some View {
        VStack {
            Text("Username")
            TextField("Enter username", text:$username)
                .frame(width: 300, height: 30)
                .border(Color.black)
            
            Text("Password")
            SecureField("Enter a password", 
                text: $password)
                .frame(width: 300, height: 30)
                .offset(x: offset)  // amount to "shake"
                .animation(
                  offset != 0 ?                   
                     Animation.default
                       .repeatCount(5).speed(4)
                    :
                    nil) // if offset is not zero, animate
                .border(Color.black)

            Button(action: {
                if true {  // simulates login failed
                    self.offset = 20 // set "shake" amount

                    // after a delay of 0.5 seconds, set 
                    // offset to 0 to bring back the 
                    // SecureField to its original 
                    // position                        
                    DispatchQueue.main.asyncAfter(
                        deadline: .now() + 0.5) {
                        self.offset = 0
                    }
                }
            }) {
                Text("Login")
            }
        }
    }
}
Posted by: Guest on August-26-2021

Code answers related to "Swift"

Browse Popular Code Answers by Language