I want to style a text using NSAttributedString
. The text should have a background and a custom padding, so that the text has a little bit of space to the background's edge.
This is what I want to achieve:
This is what I don't want to achieve (background in the second line is not word / character-specific):
And this is the code that I tried in a playground:
let quote = "some text with a lot of other text and \nsome other text."
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .left
let attributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.backgroundColor: UIColor.red,
NSAttributedString.Key.foregroundColor: UIColor.white
]
let attributedQuote = NSAttributedString(string: quote, attributes: attributes)
And this is what the playground preview renders:
[![playground preview][3]][3]
The text is very close to the edge of the background. Is there any way to get the background of the text to have some space to the text? I need some padding.
I tried using headIndent
but that would move the text with it's background to the right, not just the text. Therefor it is not useful for padding.
The best way I found is using TextKit, it's a little bit cumbersome but it's completely modular and is made for this purpose.
In my view, it isn't up to the TextView itself to draw the rectangles in its
draw
method, that's the LayoutManager's work.The entire classes used in the project are provided hereafter in order to ease the work with copy-paste (Swift 5.1 - iOS 13).
AppDelegate.swift stores the property to get the text wherever you are in the app.
ViewController.swift ⟹ only one single text view at full screen.
MyTextStorage.swift
MyLayoutManager.swift
... and here's what it looks like in the end:
There's only to customize the colors and adjust few parameters to stick to your project but this is the rationale to display a NSAttributedString with padding before and after the text and a background... for much more than 2 lines if need be.