I have a SwiftUI app with a complex dashboard view consisting of several other nested custom SwiftUI views containing SwiftUI buttons.
I want to prevent that these different buttons can be pressed simultaneously with multiple fingers and execute their actions at the same time, which is currently possible.
I could not find any solution yet which is working for me. E.g. in this SO question (How to prevent two buttons being tapped at the same time in swiftUI?) there are two solutions:
Disable
multitouchand enableexclusiveTouchin theinitof my dashboard view:UIButton.appearance().isMultipleTouchEnabled = false UIButton.appearance().isExclusiveTouch = true UIView.appearance().isMultipleTouchEnabled = false UIView.appearance().isExclusiveTouch = true
This is absolutely not working for me, neither in the init for the view, nor when I put it globally in the @main init or other global entry points of the app.
- The other approach is to have a
isEnabledstate and toggle it on every button press and set all other buttons todisabled. But this solution will not work for me, because the actual SwiftUI buttons are partly nested in multiple layers in other views.
I could not understand, that this is such a big pain in SwiftUI. Somehow it should be possible to prevent to press multiple buttons at the same time.
Any other solutions?
It's easy if you exploit an
EnvironmentObjectto manage all of the buttons in your dashboard. Let's implement the solution step by step.ButtonStylecapable of communicate with the buttons manager. This struct will tell the manager when the button is pressed/released. In order for you to check the difference between a pressed/released/enabled/disabled button I used different colors, but it's just an example, you can customize the style as you want.ViewModifierto apply to your buttons. It will be useful in order not to replicate some logic for all of your buttons in the dashboard:All you have to do is injecting the environment object in your root (whatever it is) and remember to set the modifier we've created to your buttons in the dashboard. Here's the result: