How do you make a Button conditionally hidden or disabled?

后端 未结 5 419
囚心锁ツ
囚心锁ツ 2021-01-12 14:08

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: w

5条回答
  •  北海茫月
    2021-01-12 14:46

    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)
    

提交回复
热议问题