具有多种字体颜色的 UILabel 文本
有没有办法让 UILabel
的 textColor
属性成为两个不同的 UIColors
?基本上我试图使 UILabel
text property
中的第一个字符为 greenColor
,其余为 blackColor
>。我想避免使用两个不同的 UILabels,因为我可能想更改绿色字符文本中的位置。
Is there a way to have the textColor
property of a UILabel
be two different UIColors
? Basically I'm trying to make the first character in the UILabel
text property
to be greenColor
and the rest be blackColor
. I would like to avoid using two different UILabels
because I may want to change the position in the text of the green character.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
从 ios 6 开始,您可以执行以下操作:
Starting from ios 6 you can do the following :
UILabel 不支持此属性...
使用应该使用 NSAttributedString...并使用控制器来绘制 NSAttributesString...
NSAttributedString 的控制器
更新:
从 iOS 6 开始,您可以执行以下操作:
UILabel doesnot supprt this property...
Use should use NSAttributedString... and use controllers for drawing NSAttributesString...
Controller for NSAttributedString
UPDATE:
From iOS 6 you can do the following :
Swift 3:
结果:
Swift 3:
Result:
NSAttributedStrings 支持同一字符串中的混合字体、样式和颜色,但目前任何标准 UIKit 控件都不支持。也就是说,您应该查看 TTTAttributedLabel。它是 UILabel 的简单、高性能替代品,可让您轻松显示富文本。
NSAttributedStrings support mixed fonts, styles, and colors in the same string, but aren't currently supported by any standard UIKit controls. That said, you should check out TTTAttributedLabel. It's a simple, performant replacement for UILabel that will allow you to display rich text really easily.
否 - Apple 表示,如果您需要格式化文本,则应该在
UIWebView
中使用 HTML。 (请参阅 的概述部分中的注释UITextView API 文档。)No - Apple say you should use HTML in a
UIWebView
if you need formatted text. (See the note in the overview section of the UITextView API docs.)另一种替代方法是创建多个具有不同颜色的标签并将它们彼此相邻布局。尝试使标签的背景颜色透明。这可能很乏味,但应该有用。
Another alternative way is to create multiple labels with difference color and layout them next to each other. Try to make the label's background color transparent. It may be tedious but should work.
不,这是不可能的 - 您需要自己绘制或使用多个标签进行组合。
如果您可以接受 3.2 兼容性,您可以看看
NSAttributedString
。No, that's not possible - you need to draw on your own or compose using several labels.
If you can accept 3.2 compatibility, you might have a look at
NSAttributedString
.目前还不可能,通常您会使用 NSAttributedString,但要在 iOS 上使用它,您需要滚动自己的标签。你也许可以使用 UIWebView 来解决这个问题,但我不喜欢这样做,这看起来很严厉。
not currently possible, usually you would use an NSAttributedString, but to use this on iOS you would need to roll your own label. you may be able to work round this using a UIWebView, but I don't like to do that, it seems heavy handed.