swiftswiftuifunc

How to toggle() a Bool in a non-local func with Swift?


animateButton() works great as a local func but when I move it to another swift file to use it on different Views it's broken.

I tried @State/@Binding and var isPressed = isPressed in the non-local func but it doesn't work. I also tried using inout but DispatchQueue seems to not like it.

struct ContentView: View {
    @State private var isPressed = false

    var body: some View {
        Text("Tap on me")
            .onTapGesture { animateButton() }
        Button("I'm a button", action: {})
            .scaleEffect(isPressed ? 1.20 : 1)
            .animation(.easeInOut, value: isPressed)
    }

    private func animateButtom() {
        isPressed = true
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.20) {
            isPressed = false
        }
    }
}

Do you have any ideas to make it works as a non-local func? Thanks!


Solution

  • You need to pass isPressed as a parameter and you need to make that parameter a Binding so changes in the function will update your @State property

    func animateButton(_ isPressed: Binding<Bool>) {
        isPressed.wrappedValue = true
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.20) {
            isPressed.wrappedValue = false
        }
    }
    

    and change the call to

    .onTapGesture { animateButton($isPressed) }