Home > other >  SwiftUI: underlined text does not work with background material
SwiftUI: underlined text does not work with background material

Time:06-12

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

CodePudding user response:

  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.

CodePudding user response:

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))
  • Related