gpt4 book ai didi

swift - ForegroundColor SwiftUI 上的 If else 语句

转载 作者:行者123 更新时间:2023-12-05 04:52:01 25 4
gpt4 key购买 nike

我想在按钮上做一个简单的 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"

短,但不好,我需要给自己加点颜色

那么有什么办法可以解决吗??

这是按钮的样子 enter image description here

最佳答案

持久化颜色

如果你想改变颜色并希望它继续使用那个颜色,

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

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

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

Preview 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())
}
}

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

Preview 2

关于swift - ForegroundColor SwiftUI 上的 If else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66611460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com