我正在尝试修改UILable中的属性文本,使其一行居中。因此,我使用NSParagrahStyle向NSAttributedString添加属性,如下所示
var centerParagraphAttributes : [NSAttributedString.Key : Any] {
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
return [
NSAttributedString.Key.paragraphStyle : paragraph,
NSAttributedString.Key.font : AppFonts.SFUITextBold.font(size: 14.0)
]
}
// center - or -
if let range = attributedText.string.range(of: "\n\r- or -\n\r") {
let nsrange = NSRange(range, in: attributedText.string)
attributedText.addAttributes(centerParagraphAttributes, range: nsrange)
}但是这段代码什么也不做,行和以前一样左对齐。
发布于 2019-10-10 17:31:41
好的,上面的代码可以工作并对齐文本行。我只尝试在没有"\n\r"特殊字符的子串上设置段落样式,然后将其添加到子串之后,我在"\n\r - or -\n\r"之间留出了空格,这样它就不会与range(of: "\n\r- or -\n\r")匹配
甚至在仅使用前导"\n\r- or -“时也有效,因此在段落底部不需要额外的空格
https://stackoverflow.com/questions/58319662
复制相似问题