swift - 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"
有点短,但这不好,我需要为自己添加颜色
那么有没有办法处理呢??
解决方案
保持颜色
如果您想更改颜色并且希望它继续使用该颜色,
首先你需要
State
为按钮定义一个然后你需要在按钮的动作中切换状态
最后,您使按钮的颜色有条件
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)
)
}
}
}
触地颜色
如果你想让它改变颜色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())
}
}
请注意,您可以将配置封装在样式中
推荐阅读
- javascript - Cosmos Javascript API 用于使用 Autoscale 创建集合
- swift - 如何快速在自定义导航栏顶部制作一半的 ImageView
- django - 教程:请帮助重写课程表格?
- ffmpeg - 有没有办法强制 FFMPEG 从使用 libvpx-vp9 编码的 WebM 视频中解码带有 alpha 的视频流?
- c# - 使 TryParse 在全球范围内与 CultureInfo.InvariantCulture 一起使用
- javascript - 如何将节点缓冲区打印为二进制文件?
- reactjs - 我什么时候需要在 reactJS 中使用 bind() 和 react native
- reactjs - 如何修复反应和打字稿中类型字符串上不存在的错误道具?
- flutter - 如何在我的颤振应用程序中打开本地文件(xls、文档)
- javascript - 如何不断地重新填充缓冲区/流并播放音频,而不会在缓冲区结束时出现烦人的暂停和点击声音?