如何在swiftui中动态更改文本背景颜色?

时间:2020-05-14 06:31:59

标签: swiftui

我想通过传递函数将文本背景颜色更改为.background(),像这样,color的值为0或1或2将取决于DB的数据。我该如何解决:

import SwiftUI

struct ContentView: View {
    @State var color = 0;
    var body: some View {
        Text("Hello, World!")
            .background(changeBkColor(int : self.$color))


    }
}
func changeBkColor(int : color)
{
    if(color == 1)
    {
        return Color.red;
    }
    else if(color == 2)
    {
        return Color.green;
    }
    else
    {
        return Color.blue;
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

1 个答案:

答案 0 :(得分:2)

在这里

struct ContentView: View {
    @State var color = 0;
    var body: some View {
        Text("Hello, World!")
            .background(changeBkColor(color: self.color))


    }
}
func changeBkColor(color: Int) -> Color
{
    if(color == 1)
    {
        return Color.red;
    }
    else if(color == 2)
    {
        return Color.green;
    }
    else
    {
        return Color.blue;
    }
}