简体   繁体   English

如何在 SwiftUI 中隐藏单击按钮

[英]How to hide Button on Click in SwiftUI

i want to hide one button after it's clicked and show the other and vice versa.我想在单击一个按钮后隐藏它并显示另一个按钮,反之亦然。

By default the lock button should be the one that displays first.默认情况下,锁定按钮应该是第一个显示的按钮。 After clicking on it, only the second unlock button should show in the same position.点击它后,只有第二个解锁按钮应该显示在同一个 position 中。

                  Button { //lock button
                    app.statusBar?.stop()
                   
                } label: {
                    Image(systemName: "lock")
                }
                                  
                    Button { //unlock button
                        app.statusBar?.start()
                       
                    } label: {
                        Image(systemName: "lock.open")
                    }
                }

This is for a macOS app.这是针对 macOS 应用程序的。

Why not simply one button?为什么不只是一个按钮?

@State private var isLocked = false

...
    
    Button { //lock button
        isLocked.toggle()
        if isLocked {
            app.statusBar?.stop()
        } else {
            app.statusBar?.start()
        }
    } label: {
        Image(systemName: isLocked ? "lock" :  "lock.open")
    }

If you really want two buttons you can hide one with the opacity modifier如果你真的想要两个按钮,你可以用opacity修改器隐藏一个

Button {

  ... 

}
.opacity(isLocked ? 1.0 : 0.0)

You need to set a condition through an @State variable.您需要通过@State变量设置条件。 When the variable toggles between true to false, the proper Button will be shown accordingly.当变量在真到假之间切换时,将相应地显示正确的按钮。

Here is an example:这是一个例子:

struct Example: View {
    @State private var free = true

    var body: some View {

            if free {

                Button { //lock button
                    app.statusBar?.stop()
                    free = false                   
                } label: {
                    Image(systemName: "lock")
                }

            } else {
                                  
                 Button { //unlock button
                        app.statusBar?.start()
                        free = true
                 } label: {
                        Image(systemName: "lock.open")
                 }
            }

    }
}

you could use the.hidden() modifier你可以使用 .hidden() 修饰符

Button {

  ... 

}
.hidden()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM