如何在 swift 中应用不同行间距的属性字符串
How to apply Atrributed String different spacing between lines in swift
我想在属性字符串的前两行之间应用间距,第三行应该看起来像段落。
预期输出:
Expected output screenshot
当前实施:
Current implementaion screenshot
这是我试过的代码。
let myString = "Your account phone numbers are listed here.\nTo change or delete a phone number, tap on it.\nTo add a phone number, go to the top right-hand corner of your screen and tap on “Add”.";
let font = UIFont.systemFont(ofSize: 14)
let attributedString = NSMutableAttributedString(string: myString, attributes: [.font: font])
self.displayLabel.attributedText = attributedString
我创建了标签并将行数设置为 0,因此它将显示多行文本。
在标签中需要在前两行显示 space,如预期输出屏幕截图所示。
如何仅对前两行应用间距,第三行应如预期输出屏幕截图所示显示?
您似乎想设置段落间距。这是由 NSParagraphStyle.paragraphSpacing
控制的。只需将属性字符串的 .paragraphStyle
属性设置为 NSParagraphStyle
:
let paraStyle = NSMutableParagraphStyle()
paraStyle.paragraphSpacing = 10 // or some other number
let attributedString = NSMutableAttributedString(string: myString,
attributes: [
.font: font,
.paragraphStyle: paraStyle
])
我想在属性字符串的前两行之间应用间距,第三行应该看起来像段落。
预期输出:
Expected output screenshot
当前实施:
Current implementaion screenshot
这是我试过的代码。
let myString = "Your account phone numbers are listed here.\nTo change or delete a phone number, tap on it.\nTo add a phone number, go to the top right-hand corner of your screen and tap on “Add”.";
let font = UIFont.systemFont(ofSize: 14)
let attributedString = NSMutableAttributedString(string: myString, attributes: [.font: font])
self.displayLabel.attributedText = attributedString
我创建了标签并将行数设置为 0,因此它将显示多行文本。
在标签中需要在前两行显示 space,如预期输出屏幕截图所示。
如何仅对前两行应用间距,第三行应如预期输出屏幕截图所示显示?
您似乎想设置段落间距。这是由 NSParagraphStyle.paragraphSpacing
控制的。只需将属性字符串的 .paragraphStyle
属性设置为 NSParagraphStyle
:
let paraStyle = NSMutableParagraphStyle()
paraStyle.paragraphSpacing = 10 // or some other number
let attributedString = NSMutableAttributedString(string: myString,
attributes: [
.font: font,
.paragraphStyle: paraStyle
])