Home > other >  SwiftUI: can we conditionally grey out a Confirmation Dialog button?
SwiftUI: can we conditionally grey out a Confirmation Dialog button?

Time:12-17

I have a confirmationDialog with a few buttons. In some states, a given button may not do anything useful. I can make the button disappear with...

MyButton.disabled(disableFlag)

...but this changes the dialog layout. IMHO, the dialog looks better (more consistent, familiar) with greyed out buttons.

At first I was hoping for something like this...

Button("Text", role: .disabled) { ... }

...but this won't switch.

I could set the text colour by hand, and disable what the button does. Making the text colour switch on a condition seems tricky but possible. But I am the only person developing my app, and I would much rather use some existing solution if there is one.

Am I missing something? Is there a nice way to do this?

I am using Xcode 14.1 compiling for an iPhone 12 mini running iOS 16.0. My dialog code looks like this...

    .confirmationDialog("White reference", isPresented: $showWhiteDialog) {
         Button("Set default white") {
             // (do stuff deleted)
         }.disabled(customWhite == false)
         Button("Set custom white from swatch") {
             // (do stuff deleted)
         }          
         Button("Fit swatch to white") {
             // (do stuff deleted)
         }.disabled(customWhite == false)
    }

CodePudding user response:

vadian provided the actual answer - you can't.

The real answer is not to use a Conditional Dialog, but to customise your own. If you request 'do a thing', the Conditional Dialog is the 'are you sure?' confirmation, listing possible other actions, and always including 'Cancel'. Put like this, doers does not seem to be a place for greyed out buttons.

IMHO, my use fitted this model. Adding greyed out-options meant you kept the look and feel but the dialog always had the same layout, so the user recognised it.

  • Related