首页 > 解决方案 > 使按钮处于非活动状态并更改不透明度

问题描述

我对 Swift 很陌生,所以请多多包涵。

未点击任何内容时的屏幕截图

点击一个按钮时的屏幕截图

我正在尝试将其他未点击的按钮变为非活动按钮并将不透明度更改为 0.5。

到目前为止,我已经尝试使用 $bindings 但这并没有按照我想要的方式工作。

这是我的选择按钮的代码:

struct SelectionButton: View {

var buttonText = "Selection Button"

var buttonColor = Color.white
var buttonWidth: CGFloat = 150
var active = false


var body: some View {
    
    ZStack {
        
        if active {
            
            RoundedRectangle(cornerRadius: 45)
                .frame(width: buttonWidth, height: 50)
                .foregroundColor(Color("neonGreen"))
                .shadow(color: Color(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.25)), radius:9, x:0, y:0)
            
            
            Text(buttonText)
                .font(.system(size: 18))
                .foregroundColor(.black)
                .bold()

            
        }else{
            RoundedRectangle(cornerRadius: 45)
                .frame(width: buttonWidth, height: 50)
                .foregroundColor(buttonColor)
                .shadow(color: Color(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.25)), radius:9, x:0, y:0)
            
            
            Text(buttonText)
                .font(.system(size: 18))
                .foregroundColor(.black)
            
        }
        
        
    }
    
}

这就是我使用它们的方式:

@State var gelbesBlatt = false

var body: some View {
    
    NavigationView {
        
        
        
        Button(action: {
            self.gelbesBlatt.toggle()
        }, label: {SelectionButton(buttonText: "gelb", buttonColor: .white, buttonWidth: 150, active: gelbesBlatt)
        })
    }
    
    
}

谢谢!

如果您知道如何添加组合,以便可以一起选择属于一起的特定按钮(例如“Ganzes Blatt > gelb”和“Ränder > braun”),那就太棒了!

标签: iosbuttonbindingswiftui

解决方案


检查这个:

    @State var gelbesBlatt = false
    @State var btnBraun = false
    var body: some View {
        NavigationView {
            HStack {
                Button(action: {
                    self.toggleButton(button: 0)
                }, label: {SelectionButton(buttonText: "gelb", buttonColor: .white, buttonWidth: 150, active: gelbesBlatt)
                })
                
                Button(action: {
                    self.toggleButton(button: 1)
                }, label: {SelectionButton(buttonText: "braun", buttonColor: .white, buttonWidth: 150, active: btnBraun)
                })
            }
        }
    }
    func toggleButton(button: Int) {
        if(button == 0) {
        self.gelbesBlatt = true
        self.btnBraun = false
    } else {
        self.gelbesBlatt = false
        self.btnBraun = true
    }
        self.gelbesBlatt.toggle()
        self.btnBraun.toggle()
    }

推荐阅读