Search code examples
swiftswiftuitext

Add padding to text background color


I want to make the text appear "highlighted" but not the whole text box. I'd like for each line to be individually highlighted. I've not found the best way to make this happen. The only thing I can think of is to use the same text from my variable, putting a background color on it, lower the font to where it makes a gap and make the text color clear... if that makes sense. Here is what I'm wanting. I'm using SwiftUI. Any help would be much appreciated.

For what it matters this is what I'm using to achieve my text alignment.

struct LabelAlignment: UIViewRepresentable {
    var text: String
    var textAlignmentStyle : TextAlignmentStyle
    var width: CGFloat
    var fontName: String
    var fontSize: CGFloat
    var fontColor: UIColor

    func makeUIView(context: Context) -> UILabel {
        let font = UIFont(name: fontName, size: fontSize)
        let label = UILabel()
        label.textAlignment = NSTextAlignment(rawValue: textAlignmentStyle.rawValue)!
        label.numberOfLines = 0
        label.preferredMaxLayoutWidth = width
        label.font = font
        label.setContentHuggingPriority(.required, for: .horizontal)
        label.setContentHuggingPriority(.required, for: .vertical)
        label.textColor = fontColor

        return label
    }

    func updateUIView(_ uiView: UILabel, context: Context) {
        uiView.text = text
    }
}

enum TextAlignmentStyle : Int{
     case left = 0 ,center = 1 , right = 2 ,justified = 3 ,natural = 4
}

enter image description here


Solution

  • Attributed text with line spacing and background color

    func updateUIView(_ uiView: UILabel, context: Context) {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 15
        paragraphStyle.alignment = NSTextAlignment(rawValue: textAlignmentStyle.rawValue)!
        let attributedText = NSAttributedString(
            string: "This is a quote from my favorite book. I will put many more of these quotes on this list. Enjoy for now thank you",
            attributes: [
                .backgroundColor: UIColor.yellow,
                .paragraphStyle: paragraphStyle,
            ])
        uiView.attributedText = attributedText
    }