swift - SwiftUI Text 前景色变成背景色
问题描述
似乎为了更改字体/文本颜色,建议使用前景属性。当我将该颜色设置为黑色时,它也会更改胶囊颜色。如何仅指定文本以更改颜色?
import SwiftUI
struct CapsuleButtonFilled: View {
// MARK: - PROPERTIES
var backgroundColor: Color
// MARK:
var body: some View {
Button(action: {}, label: {
Text("The Solid")
.background(backgroundColor)
.foregroundColor(Color.black)
.padding()
})
.background(
Capsule(style: .circular)
.background(backgroundColor)
)
}
}
struct CapsuleButtonFilled_Previews: PreviewProvider {
static var previews: some View {
CapsuleButtonFilled(backgroundColor: .orange)
.previewLayout(.sizeThatFits)
}
}
解决方案
当我将该颜色设置为黑色时,它也会更改胶囊颜色。
的默认填充颜色Capsule
为黑色。例如,这是一个Capsule
没有应用任何内容的平原。
struct CapsuleButtonFilled: View {
var body: some View {
Capsule(style: .circular)
}
}
struct CapsuleButtonFilled_Previews: PreviewProvider {
static var previews: some View {
CapsuleButtonFilled()
.previewLayout(.fixed(width: 400, height: 100))
}
}
结果:
假设您设置Color.green
了文本颜色。
Button(action: {}, label: {
Text("The Solid")
.foregroundColor(Color.green) /// green!
.background(backgroundColor)
.padding()
})
.background(
Capsule(style: .circular)
.background(backgroundColor)
)
这是结果:
.foregroundColor()
应用于Text
不影响胶囊。
无论如何,我认为这是您想要的结果?
您使用错误的修饰符将颜色应用于胶囊。使用.fill()
而不是.background()
.
Button(action: {}, label: {
Text("The Solid")
.foregroundColor(Color.black)
.background(backgroundColor)
.padding()
})
.background(
Capsule(style: .circular)
.fill(backgroundColor)
)
推荐阅读
- python - 使用python找到多维模型的最佳参数集
- python - 经过时间后删除散点图中的一个点 - matplotlib
- shopify - 如何仅在特定页面上加载脚本标签?(购物)
- typescript - 导入webpack或htmlWebpackPlugin后构建webpack的几个错误
- google-cloud-platform - 写入 BigQuery 表的最低 IAM 权限?
- python - Django 中的 OpenTelemetry Python Auto Instrumentation 出现错误
- node.js - Node JS 不使用 SendGrid
- gitlab-api - gitlab api v4 未读取所有组标签
- flutter - 任务“:mecab_dart:externalNativeBuildDebug”执行失败
- python - 将多个数值列转换为值和类别列