如何使按钮有条件地隐藏或禁用? [英] How do you make a Button conditionally hidden or disabled?

查看:238
本文介绍了如何使按钮有条件地隐藏或禁用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何切换按钮的隐藏状态?


我们拥有无条件的.hidden()属性;但我需要有条件的版本。


注意:我们确实有 .disabled(bool)属性可用,但没有 .hidden(bool)属性。

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.
            }
        }
    }
}


推荐答案

对我来说,当您不想看到它时,将 frame 的高度设置为零是完美的。如果要获得计算出的大小,只需将其设置为 nil

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)

如果要除了隐藏它之外,还可以禁用它,您可以使用切换后的布尔值设置 .disabled

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)

这篇关于如何使按钮有条件地隐藏或禁用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆