Challenge: SwiftUI State |

This is a companion discussion topic for the original entry at
1 Like

Do not really understand something. If I change the alert isPresented parameter of the new alert to the previous one, like in this example:

Button(action: {
self.knockKnockIsVisible = true

        }) {
            Text("Knock, knock")
        .alert(isPresented: $alertIsVisible,
               content: {
            return Alert(title: Text("Who's there?"), message: Text("Little old lady."), dismissButton: .default(Text("Little old lady who?")))

Then, the first dialog will be shown. How the isPresented parameter working? In the action, I set the correct value on the self.knockKnockIsVisible. If the .alert method is called on the second button, why the first dialog is shown?

Or, to put it another way, if I want to use the same variable (alertIsVisible) for multiple alerts, the .alert() method will always display the first registered content, not the one returned on the actual button pressed.

Hi @lollipopdevintralink, the issue here is that both alerts are added in the same view hierarchy. When you add a new alert after Button, gets added to same view hierarchy, at the moment SwiftUI doesn’t support multiple alerts/sheets in the way you want to.

I’ll recommend using just one alert and change the content based on a state variable. Like this:

.alert(isPresented: $alertIsVisible, content: { 
     return showFirsAlert ? content1 : content2

Thanks @libranner for your answer.
Something seems strange to me, being used to the previous way of implement UI.

The alert method is the one that triggers the dialog, but it seems to take into account the isPresented parameter and not the button instance on which is called.

I didnt use the self keyword to change the state i just wrote alertIsVisible = true and it still works but why is that ? why we have to write self.alertIsVisible instead of simple alertIsVisible ?