Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make a Button conditionally hidden or disabled?

Tags:

button

swiftui

How do I toggle the presence of a button to be hidden or not?
We have the non-conditional .hidden() property; but I need the conditional version.

Note: we do have the .disabled(bool) property available, but not the .hidden(bool).

struct ContentView: View {
    var body: some View {
        ZStack {
            Color("SkyBlue")
            VStack {
                Button("Detect") {
                    self.imageDetectionVM.detect(self.selectedImage)
                }
                .padding()
                .background(Color.orange)
                .foreggroundColor(Color.white)
                .cornerRadius(10)
                .hidden() // ...I want this to be toggled.
            }
        }
    }
}
like image 520
Frederick C. Lee Avatar asked Aug 08 '19 20:08

Frederick C. Lee


People also ask

How do I enable and disable a button in SwiftUI?

SwiftUI lets us disable any part of its forms or even the whole form, all by using the disabled() modifier. This takes a single Boolean that defines whether the element should be disabled or not. The form element's style automatically gets updated to reflect its status – buttons and toggles get grayed out, for example.

How do I hide Show View in SwiftUI?

If you need to reserve space in a layout based on the measurement of a view, but never want to show that view, you can use the hidden() modifier.


1 Answers

all the answers here works specifically for a button to be hidden conditionally.

What i think might help is making a modifier itself conditionally e.g: .hidden for button/view, or maybe .italic for text, etc..

Using extensions.

For text to be conditionally italic it is easy since .italic modifier returns Text:

extension Text {
    func italicConditionally(isItalic: Bool) -> Text {
        isItalic ? self.italic() : self
    }
}

then applying conditional italic like this:

@State private var toggle = false
Text("My Text")
    .italicConditionally(isItalic: toggle)

However for Button it is tricky, since the .hidden modifier returns "some view":

extension View {
    func hiddenConditionally(isHidden: Bool) -> some View {
        isHidden ? AnyView(self.hidden()) : AnyView(self)
    }
}

then applying conditional hidden like this:

@State private var toggle = false
Button("myButton", action: myAction)
    .hiddenConditionally(isHidden: toggle)
like image 166
Esam Sherif Avatar answered Sep 21 '22 16:09

Esam Sherif