NSAttributedString 插入项目符号点?
所以我有一个 NSAttributedString 我想在文本部分的开头插入一个项目符号点。我该怎么做?如何创建一个在显示文本时创建此项目符号点的 CTPAragraphStyle
?
编辑: 应可在 iOS 上使用
So I have an NSAttributedString
I want to insert a bullet point
at the beginning of a portion of text. How can I do this? How do I create a CTPAragraphStyle
that creates this bullet point when I display the text?
Edit:
Should be available on iOS
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这是一种适用于 iOS6 的更现代的方法:
Here's a more modern approach that works from iOS6:
这是一个很好的解决方案,使用 Swift
添加项目符号属性
Swift 4.2++
Swift 4.0 & 4.1
结果如下:
Here is nice solution with Swift
Add bullet attributes
Swift 4.2++
Swift 4.0 & 4.1
Here is result:
简单一点: [mutableAttributedString insertAttributedString: @"•\t" atIndex:0];
最难的一点。大致如下。 (这是从一个更大的项目中提取的,但它可能会给您一个不错的开始。)
您需要包含 CoreText 框架,然后导入 CoreText/CoreText.h
The easy bit: [mutableAttributedString insertAttributedString: @"•\t" atIndex:0];
The hard bit. Something along the following lines. (This is extracted from a bigger project, but it may give you a decent start.)
You need to include the CoreText framework and then import CoreText/CoreText.h
您不会在 iOS 中实现带有段落样式的项目符号列表。根据需要设置制表位,然后在段落开头插入制表符、项目符号、制表符。
CTParagraphStyle
非常不灵活,因此您不能只向其中添加您选择的新样式。不过,您可以将任何您喜欢的属性 (MYBulletStyle
) 添加到NSAttributedString
内的任意运行中。这对于使用NSAttributedString
传递项目符号列表信息非常有用,然后在准备显示它时重建字符串以包含项目符号。但核心文本不会自动为您呈现项目符号。You don't implement a bulleted list with a paragraph style in iOS. Set your tab stops as you'd like, and then insert a tab, bullet, tab at the beginning of the paragraph.
CTParagraphStyle
is quite inflexible, so you can't just add new styles of your choosing to it. You can, however, add any attribute you like (MYBulletStyle
) to arbitrary runs within theNSAttributedString
. This can be useful for passing the bullet-list information around with theNSAttributedString
and then rebuilding the string to include the bullets when you're ready to display it. But Core Text won't render the bullets for you automatically.这是 Krunal 在 Objective-C 中的出色回答。它还删除了最后一个项目符号项上的段落间距,以避免 UILabel 上出现额外的底部填充。
这是创建实际属性文本的函数:
Here is Krunal's excellent answer in Objective-C. It also removes the paragraph spacing on the last bullet item to avoid the extra bottom padding on the UILabel.
And here is the function which creates the actual attributed text:
不是这个问题的实际答案,但这可以提供帮助。
只需添加“•”
即使我正在为我的textView寻找类似的东西。我所做的,只需将我的字符串附加到上面的字符串并将其传递给我的 textView,标签也可以这样做。我为未来的观众回答了这个问题。
Not the actual answer for this question but this can help.
just add " • "
Even i was looking for something like this for my textView. What i did, just append above string with my string and pass it to my textView, same can be done for labels also. I answered this for future Viewer.
另一个对 @krunal 答案的重复,这次稍微简化为 Swift 5 中的 NSAttributedString 初始值设定项:
Another riff on @krunal's answer, this time slightly simplified as an NSAttributedString initializer in Swift 5: