SwiftUI Multiple AlertView, fix weird SwiftUI Alert Behavior
Unlike SwiftUI, which helps you write code intuitively, Alert seems to be implemented strangely. Once an alert is defined in the parent view, all alerts in the child view are ignored. I don’t know if it’s a bug in SwiftUI or it’s intended, but if you use alert, it’s rare to use just one alert.
Will this code work as intended? Not really. Only alert1 will show. Because as I told you, once you defined alert in parent view, all child view alerts are ignored.
Fix #1-Define multiple alerts in the same hierarchy
This will make your code work as intended.
Fix #2-Add Conditional Statement
I mostly use this approach. But the solution #1 is not bad. Instead of defining multiple alert at the same level of the view, I created enum to divide alert types.
- Once an alert is defined in the parent view, all alerts in the child view are ignored.
- To solve this problem, define multiple alerts at the same hierarchy level.
- Or just show different alerts using conditional statement.