NSAttributedString如何使用NSParagraphStyle设置文本中心对齐线

问题描述 投票:0回答:1

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

但是此代码不执行任何操作,并且行像以前一样保持对齐。

我正在尝试将UILable中的属性文本修改为以一行为中心。因此,我使用NSParagrahStyle将属性添加到NSAttributedString中,如下所示:var centerParagraphAttributes:[...

ios swift nsattributedstring
1个回答
0
投票

确定,以上代码可以工作并对齐文本行。我只尝试在不带"\n\r"特殊字符的子字符串上设置段落样式,而这些字符不能启动新段落,然后将其添加到子字符串后,我在"\n\r - or -\n\r"之间留了空白,因此它与range(of: "\n\r- or -\n\r")不匹配

甚至在仅使用前导“ \ n \ r-或-”时它甚至都可以使用,因此在段落底部不需要多余的空间

© www.soinside.com 2019 - 2024. All rights reserved.