gpt4 book ai didi

ios - NSAttributedString 如何使用 NSParagraphStyle 设置文本行居中对齐

转载 作者:行者123 更新时间:2023-11-29 05:24:27 25 4
gpt4 key购买 nike

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

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

最佳答案

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

更重要的是,当仅使用前导“\n\r- 或 -”时,它甚至可以工作,因此段落底部不需要额外的空间

关于ios - NSAttributedString 如何使用 NSParagraphStyle 设置文本行居中对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58319662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com