ios - 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)
}
但是这段代码没有做任何事情,并且行像以前一样左对齐。
解决方案
好的,上面的代码可以正常工作并对齐文本行。我只尝试在没有"\n\r"
开始新段落的特殊字符的情况下在子字符串上设置段落样式,然后在将其添加到子字符串之后,我在它们之间留下了空白空间"\n\r - or -\n\r"
所以它不匹配range(of: "\n\r- or -\n\r")
更重要的是,它甚至在仅使用前导“\n\r- 或 -”时也有效,因此段落底部不需要额外的空间
推荐阅读
- c# - 如何在 C# 的并行任务中通过 tcp 套接字接收数据?
- symfony - 如何通过 JsFormValidatorBundle 验证的表单的 ajax 部分进行更改
- angular - 如何使用 angular 2 在prime ng中一次显示一个日历
- javascript - 在服务器上发布后,asp.net mvc ajax 调用不调用控制器
- java - JLS、JSR 和 JEP 之间有什么区别(或关系)?
- c# - 如何更改 Unity Text 中的文本
- mongodb - 如何根据MongoDB中where条件中引用的文档详细信息获取父文档详细信息?
- qemu - qemu-system-aarch64 从来宾系统内退出
- typescript - 用茉莉花测试打字稿联合类型
- c# - ASP.NET MVC5 使用特定选定数据“分支”向用户显示数据