首页 > 解决方案 > ForegroundColor SwiftUI 上的 If else 语句

问题描述

我想在按钮上做一个简单的 if-else 语句

Button(action: {self.theSoal = nomor.id}) {
            Circle()
                .frame(width:80,height: 80, alignment:.center)
                .foregroundColor(.blue)
                .overlay(
                    Text("99")
                        .font(.title)
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                    
                )
        }

看到那个.blue,所以我想要一个条件语句,如果单击按钮,那么颜色会从.blue变为.yellow

我该怎么做??到目前为止,我的选择是使用状态?

state color = "blue"

if the button is pushed then color = "yellow"

有点短,但这不好,我需要为自己添加颜色

那么有没有办法处理呢??

这是按钮的样子 在此处输入图像描述

标签: swiftswiftui

解决方案


保持颜色

如果您想更改颜色并且希望它继续使用该颜色,

  1. 首先你需要State为按钮定义一个

  2. 然后你需要在按钮的动作中切换状态

  3. 最后,您使按钮的颜色有条件

struct ContentView: View {

    @State var isActive = false // <- Check this out

    var body: some View {

        Button {
            theSoal = nomor.id
            isActive.toggle() // <- Check this out
        } label: {
            Circle()
                .frame(width: 80, height: 80, alignment:.center)
                .foregroundColor(isActive ? .blue : .yellow) // <- Check this out
                .overlay(
                    Text("99")
                        .font(.title)
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                )
        }
    }
}

预览 1


触地颜色

如果你想让它改变颜色touch-down并恢复颜色,touch-up那么你需要定义一个自定义样式:

struct CustomButton: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .frame(width: 80, height: 80, alignment:.center)
            .font(Font.title.weight(.bold))
            .foregroundColor(.white)
            .background(configuration.isPressed ? Color.yellow : .blue) // <- Check this out
            .clipShape(Circle())
    }
}

使用代码如下:

struct ContentView: View {

    var body: some View {
        Button("99") { theSoal = nomor.id }
        .buttonStyle(CustomButton())
    }
}

请注意,您可以将配置封装在样式中

预览 2


推荐阅读