How do you make a Button conditionally hidden or disabled?

后端 未结 5 465
囚心锁ツ
囚心锁ツ 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 15:04

    You can utilize SwiftUI's new two-way bindings and add an if-statement as:

    struct ContentView: View {
    
        @State var shouldHide = false
    
        var body: some View {
            ZStack {
                Color("SkyBlue")
                VStack {
                    if !self.$shouldHide.wrappedValue { 
                        Button("Detect") {
                            self.imageDetectionVM.detect(self.selectedImage)
                        }
                        .padding()
                        .background(Color.orange)
                        .foregroundColor(Color.white)
                        .cornerRadius(10)
                    }
                }
            }
        }
    }
    

    The benefit of doing this over setting the opacity to 0 is that it will remove the weird spacing/padding from your UI caused from the button still being in the view, just not visible (if the button is between other view components, that is).

提交回复
热议问题