可能的解决方案是:
- 在storyboard\xib中设置paragraphStyle相关属性(lineHeightMultiplier、alignment等);(截图一,截图二)
- 在更改标签的属性文本之前获取段落样式;
- 创建您需要的属性字符串;
- 将paragrapshStyle属性添加到属性字符串;
- 将创建的属性字符串设置为属性文本属性。
如果不使用任何 syntax-sugar-lib,它可能看起来像这样:
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
使用 pod 'SwiftyAttributes' 和 NSMutableAttributedString 扩展:
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)
}
}
代码将是:
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)