Search code examples
swiftxcodetextswiftuibackground

SwiftUI: underlined text does not work with background material


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


Solution

  •   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.