首页 > 解决方案 > 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)
    }
}

在此处输入图像描述

标签: swift

解决方案


当我将该颜色设置为黑色时,它也会更改胶囊颜色。

的默认填充颜色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)
)

推荐阅读