在我的iOS应用程序中,我使用NSAttributedString来生成一个项目符号列表。不幸的是,我在使这些项目符号看起来好看方面遇到了困难。我的第一次尝试是使用常规文本和Unicode字符来表示项目符号,基本上使用像这样的字符串:
var attributedString = NSMutableAttributedString(
string: "Here is a list of bullets and a paragraph introducing them, note that this paragraph spans multiple lines\n" +
"• This is the first bullet\n" +
"• Here is a second bullet\n" +
"• And here is a third bullet with a lot of text such that it overflows to the next line"
)
结果如下:
我喜欢这些项目符号的外观,但是最后一个项目符号中溢出的文本应该与前一行对齐,我无法通过纯文本实现这一点(而不将相同的对齐方式应用于上面的段落)。
我的第二次尝试是使用NSAttributedString中的NSHTMLTextDocumentType进行HTML处理,并使用<ul>
和<li>
元素生成项目符号。
let content = "Here is a list of bullets and a paragraph introducing them, note that this paragraph spans multiple lines" +
"<ul>" +
"<li>This is the first bullet</li>" +
"<li>Here is a second bullet</li>" +
"<li>And here is a third bullet with a lot of text such that it overflows to the next line</li>" +
"</ul>"
var attributedString = try! NSMutableAttributedString(
data: content,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil
)
问题已经解决了,但引入了一个新的问题:
现在项目符号之间的距离太远了(从左边缘和右边的文本都太远)。我尝试使用典型的HTML/CSS技巧来修复对齐问题(<li style="text-indent: -10px;">
),但这些样式似乎被NSAttributedString忽略了。
我尝试使用另外一个NSMutableParagraphStyle来解决这个问题,但它似乎带来了更多的问题。下面是我尝试过的内容:
var paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = 0
paragraphStyle.headIndent = 20
attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: attributedStringRange)
这是我得到的:
正如您所看到的,它只会使事情变得更糟,以下是我的问题:
- 虽然它确实偏移了第二行,但我只希望该效果适用于项目符号,而不是段落前面(我想我可以通过减少应用效果的范围来弥补这一点)
- 我必须猜测/硬编码偏移量,在我的示例中,我选择了20,但对于给定的当前字体设置,这对于项目符号来说还不够,而这些设置可能会发生变化
- 由于某种原因,无缘无故地拉伸了项目符号间距,似乎只需应用普通的NSParagraphStyle就会出现这种情况,我看不到任何修复此问题的选项。
我真正想要的是,我的项目符号间距看起来类似于第一个屏幕截图,同时第二行的溢出缩进看起来像第二个屏幕截图,而无需硬编码精确的像素位置。你们能帮帮我吗?
谢谢