2

I'm trying to recreate the HTML span background coloring effect in SwiftUI. Not the whole bounding view should be colored, only the text lines. Can this be done easily in SwiftUI / UIKit / Core Graphics ?

div {
  max-width: 400px;
  line-height: 2;
  font-family: sans-serif;
}

span {
  background-color: blue;
  color: white;
  padding: 0.3em;
}
<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed varius, nulla eget consequat finibus, tortor erat scelerisque ipsum, nec dictum justo quam in ipsum. Nulla nec eleifend felis. Sed vel semper mauris, a placerat elit.</span>
</div>
struct ContentView: View {
    var body: some View {
        Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed varius, nulla eget consequat finibus, tortor erat scelerisque ipsum, nec dictum justo quam in ipsum. Nulla nec eleifend felis. Sed vel semper mauris, a placerat elit.")
            .foregroundColor(.white)
            .background(Color.blue)
            .frame(maxWidth: 200)
            .lineSpacing(6)
    }
}

SwiftUI Preview: SwiftUI Preview

TD540
  • 1,728
  • 3
  • 14
  • 26

1 Answers1

0

Closest solution this moment seems to be to ‘hack it’ using AttributedString, which is not the most elegant… And adding padding between background and text seems impossible.

struct ContentView: View {
    let text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed varius, nulla eget consequat finibus, tortor erat scelerisque ipsum, nec dictum justo quam in ipsum. Nulla nec eleifend felis. Sed vel semper mauris, a placerat elit."
    var attributedString: AttributedString {
        var attributedString = AttributedString(text)            
        attributedString.foregroundColor = .white
        attributedString.backgroundColor = .blue
        return attributedString
    }
    var body: some View {
        Text(attributedString)
            .frame(maxWidth: 300)
            .lineSpacing(6)
    }
}

Really wish it were possible to use the text baselines as a CGPath and add multiple rectangles.

TD540
  • 1,728
  • 3
  • 14
  • 26