Home > other >  Multiple action for a single button swiftUI
Multiple action for a single button swiftUI

Time:02-05

I want to place multiple actions for one button so that I can move freely with a press of a button.

                              Button(action: {
                                withAnimation {
                                   viewModel.sendCode()
                                }

want to create another action to go to WelcomeView (like action :goWelcome()) but it is not working together.

                            }, label: {
                                Text("Send Phone Number")
                                    .font(.headline)
                                    .fontWeight(.bold)
                                    .foregroundColor(.blue)
                                    .frame(maxWidth: .infinity, maxHeight: 60)
                                    .background(Color("Primary"))
                                    .cornerRadius(6)
                                    .shadow(color: Color("Primary").opacity(0.8), radius: 6, x: 1, y: 1)
                                    
                            })




  func goWelcome() {
  if let window = UIApplication.shared.windows.first {
    window.rootViewController = UIHostingController(rootView: WelcomeView())
    window.makeKeyAndVisible()
}

}

CodePudding user response:

If you want to do multiple things on one press, simply add more things in the action's {}:

Button(action: {
            withAnimation {
                viewModel.sendCode()
            }

            goWelcome()          
        }, label: {
            Text("Send Phone Number")
})

If you want to have multiple gestures at once, use .simultaneousGesture(). e.g. if you want to have an extra action after holding the button for certain time:

Button(action: {
            withAnimation {
                viewModel.sendCode()
            }       
        }, label: {
            Text("Send Phone Number")
}).simultaneousGesture(LongPressGesture(minimumDuration: 2).onEnded { _ in
    goWelcome()
})

minimumDuration: is the time in seconds after which an action happens

  •  Tags:  
  • Related