How do you make a Button conditionally hidden or disabled?

I hope hidden modifier gets argument later, but since then, Set the alpha instead:

@State var shouldHide = false

var body: some View {
    Button("Button") { self.shouldHide = true }
    .opacity(shouldHide ? 0 : 1)
}

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)

For me it worked perfectly to set the frame's height to zero when you do not want to see it. When you want to have the calculated size, just set it to nil:

SomeView
    .frame(height: isVisible ? nil : 0)

If you want to disable it in addition to hiding it, you could set .disabled with the toggled boolean.

SomeView
    .frame(height: isVisible ? nil : 0)
    .disabled(!isVisible)

Tags:

Button

Swiftui