How to:使用Swift UI设置文本的背景色

时间:2020-07-01 20:44:24

标签: swift swiftui

我正在使用快速的UI,并且在创建视图时无法弄清楚如何使添加到视图中的文本具有与视图本身相同的背景色。在下面的视图之外,StrokeText()保持白色背景。

struct ContentView: View {
    
    var body: some View {
        VStack {
               HStack {
                   VStack(alignment: .leading) {
                    StrokeText(text: "App Name", width: 1.0, color: .black)
                        .background(Color.init(hue: 0.2722, saturation: 0.89, brightness: 0.29, opacity: 1.0))
                            .foregroundColor(.white)
                            .font(.system(size: 30, weight: .bold))
                    
                    .frame(maxWidth: .infinity, alignment: .center)

                    //Background Color
                          Color.init(hue: 0.2722, saturation: 0.89, brightness: 0.29, opacity: 1.0).edgesIgnoringSafeArea(.all)
                 
                       }
                   }
               }
      
    }
}

struct StrokeText: View {
    let text: String
    let width: CGFloat
    let color: Color

    var body: some View {
        ZStack{
            ZStack{
                Text(text).offset(x:  width, y:  width)
                Text(text).offset(x: -width, y: -width)
                Text(text).offset(x: -width, y:  width)
                Text(text).offset(x:  width, y: -width)
               
            }
            .foregroundColor(color)
            Text(text)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

这是张图片供参考

app issue

1 个答案:

答案 0 :(得分:0)

我不确定我了解您想要的最终效果是什么,但是如果您只是想让标签上的绿色背景边缘到边缘,只需将背景修饰符移动到框架下方:

StrokeText(text: "App Name", width: 1.0, color: .black)
                        .foregroundColor(.white)
                        .font(.system(size: 30, weight: .bold))
                        .frame(maxWidth: .infinity, alignment: .center)
                        .background(Color.init(hue: 0.2722, saturation: 0.89, brightness: 0.29, opacity: 1.0))