简体   繁体   中英

how to change the text background color dynamically in swiftui?

I want change the text background color with passing function to the.background()like this, the value of color is 0 or 1 or 2 will depend on the data of DB.how can I fix it:

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

Here it is

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM