The possible solution is:
- set up paragraphStyle related attributes (lineHeightMultiplier, alignment etc.) in storyboard\xib; (screenshot 1, screenshot 2)
- get paragraphStyle before changing the attributed text of a label;
- create attributedString you need;
- add paragrapshStyle attribute to attributedString;
- set created attributedString as attributedText property.
Without using any syntax-sugar-lib it may look like this:
func paragraphStyle(in attrString: NSAttributedString?) -> NSParagraphStyle? {
return attrString?.attribute(NSParagraphStyleAttributeName, at: 0, effectiveRange: nil) as? NSParagraphStyle
}
let text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
let attributedText = NSMutableAttributedString(string: text, attributes: [
NSFontAttributeName: UIFont.systemFont(ofSize: 20.0),
NSForegroundColorAttributeName: UIColor.orange
])
if let paragraphStyle = paragraphStyle(in: label.attributedText) {
let textRange = NSMakeRange(0, text.characters.count)
attributedText.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: textRange)
}
label.attributedText = attributedText
Using pod 'SwiftyAttributes' and NSMutableAttributedString extension:
import SwiftyAttributes
extension NSMutableAttributedString {
func withParagraphStyle(from attrString: NSAttributedString?) -> NSMutableAttributedString {
guard let attrString = attrString, let pStyle = attrString.attribute(.paragraphStyle, at: 0) else {
return self
}
return self.withAttribute(pStyle)
}
}
code will be:
let text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
label.attributedText = text.withAttributes([
.font(.systemFont(ofSize: 20.0)),
.textColor(.orange)
]).withParagraphStyle(from: label.attributedText)