skip to Main Content

When I tried to display an underlined text with background material, I faced a problem

After some work around, I succeeded in creating the minimal test case that does not work as I expect

Could you please tell me, that is my wrong expectations, or I just missed something?

BTW: That works fine with other text modifiers, such as .bold() or .italic()

Here is an example to reproduce the bug:

var body: some View {
    ZStack {
        LinearGradient(colors: [.orange, .yellow, .red], startPoint: .topLeading, endPoint: .bottomTrailing)
                .ignoresSafeArea()
        Text("Some underlined text")
            .underline()
            .padding()
            .background(.ultraThinMaterial)
    }
}

enter image description here

Works fine:

var body: some View {
    ZStack {
        LinearGradient(colors: [.orange, .yellow, .red], startPoint: .topLeading, endPoint: .bottomTrailing)
                .ignoresSafeArea()
        Text("Some underlined text")
            .underline()
            .padding()
            .background(.white)
    }
}

enter image description here

2

Answers


  1. It’s probably looks like bug. But you can use next modifier to achieve normal behavior

    struct Blur: UIViewRepresentable {
        var style: UIBlurEffect.Style = .systemMaterial
        func makeUIView(context: Context) -> UIVisualEffectView {
            return UIVisualEffectView(effect: UIBlurEffect(style: style))
        }
        func updateUIView(_ uiView: UIVisualEffectView, context: Context) {
            uiView.effect = UIBlurEffect(style: style)
        }
    }
    

    Implement it to your text view

    Text("Some underlined text")
        .underline()
        .padding()
        .background(Blur(style: .systemUltraThinMaterial))
    
    Login or Signup to reply.
  2.   var body: some View {
        ZStack {
            LinearGradient(colors: [.orange, .yellow, .red], startPoint:            .topLeading, endPoint: .bottomTrailing)
                    .ignoresSafeArea()
            Text("Some underlined text")
                .underline()
                .padding()
                .background(
                    Rectangle() //Add this one line of code
                        .fill(.ultraThinMaterial)
                )
        }
    }
    

    Add this one to your code will fix your problem.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search