首页 > 解决方案 > NSAttributedString 如何使用 NSParagraphStyle 设置文本行居中对齐

问题描述

我正在尝试修改 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)
            }

但是这段代码没有做任何事情,并且行像以前一样左对齐。

标签: iosswiftnsattributedstring

解决方案


好的,上面的代码可以正常工作并对齐文本行。我只尝试在没有"\n\r"开始新段落的特殊字符的情况下在子字符串上设置段落样式,然后在将其添加到子字符串之后,我在它们之间留下了空白空间"\n\r - or -\n\r"所以它不匹配range(of: "\n\r- or -\n\r")

更重要的是,它甚至在仅使用前导“\n\r- 或 -”时也有效,因此段落底部不需要额外的空间


推荐阅读