3

I have a .navigationBarItems button that I want to enable/disable depending on what my app is doing but I cannot for the life of me figure out how the heck to do this?!

My view is being pulled into my main app view via a NavigationView so I know the bar items are being shown correctly and whatnot. On my view that's being pulled in upon navigating to it I have this code at the bottom of the stack:

.navigationBarItems(
                    trailing:
                        Button("End Day") {
                            //do something here
                            scheduleEndDayNotificatons()
                        }
                    )

I'd like to be able to toggle the trailing "End Day" button to be enabled/disabled, probably based on some Bool state variable? Such as when the user enters into a mode of the app it's enabled, when they exit that mode it's disabled. My app is an exercise app, so when they're working out I'd want it to be enabled and when they finish working out it's disabled (which is the default).

Any help would be very much appreciated! Thank you!!

jammyman34
  • 1,399
  • 4
  • 15
  • 22

1 Answers1

3

We can use modifier .disabled applied to Button and link it with some state variable, like

@State private var isDisabled = false

// ... other code

.navigationBarItems(
    trailing:
        Button("End Day") {
            //do something here
            scheduleEndDayNotificatons()
        }
        .disabled(isDisabled)
    )
Asperi
  • 228,894
  • 20
  • 464
  • 690