如何分配 NSString UIColor
有没有一种方法可以将 UIColor 分配给 NSString 就像
cell.textLabel.text = [UIColor grayColor];
我试图为以下字符串添加颜色一样:
NSString *text = @"Hello"
[text setColor:[UIColor grayColor]; // It gives error here saying it cannot assign
还有其他方法可以将颜色分配给 NSString 吗?
Is there a way I can assign UIColor to NSString like in
cell.textLabel.text = [UIColor grayColor];
I am trying to add color for following string like :
NSString *text = @"Hello"
[text setColor:[UIColor grayColor]; // It gives error here saying it cannot assign
Is there any other way I can assign color to NSString ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
NSString 只是一个字符串。它没有颜色、字体、粗细、大小、样式或任何东西——只有字符。您需要使用 NSAttributedString 代替。
但请记住,NSAttributedString 不是 NSString - 它基本上是一个轻量级容器,它将字符串与属性字典配对并提供适当的绘图代码。特别是,您不能将 NSAttributedString 传递给需要字符串的 API。您要么必须有一个接受 NSAttributedString 的 API,要么自己绘制字符串。
NSString is just a string of characters. It doesn't have a color, font, weight, size, style or anything — just characters. You'll want to use NSAttributedString instead.
But bear in mind that NSAttributedString isn't an NSString — it's basically a lightweight container that pairs a string with a dictionary of attributes and provides appropriate drawing code. In particular, you can't pass an NSAttributedString to an API that expects a string. You either have to have an API that takes an NSAttributedString or be drawing the string yourself.
您不能为字符串指定颜色。字符串没有有关颜色的数据。您可以为标签分配颜色,例如
您必须等到显示字符串才能设置颜色。如果需要,您可以将颜色存储在 UIColor * 类型的变量中,直到稍后。
You can't assign a color to a string. A string doesn't have data about color. You can assign a color to a label, like
You have to wait until you display the string to set the color. If you need to, you can store the color in a variable of type UIColor * until later.
您无需在绳子上设置颜色,而是在标签上设置颜色。字符串只是一个字符序列 - 标签负责显示它并控制颜色等内容。
查看 UILabel 类参考 并查找 textColor 属性。
在你的例子中,我认为你想要:
You don't set the color on the string, you set it on the label. The string is just a sequence of characters - the label is responsible for displaying it and so controls things like color.
Take a look at UILabel class reference and look for the textColor property.
In your example, I think you want:
https://github.com/AliSoftware/OHAttributedLabel
1.上面是来自 github 的 4 个文件的链接下载并将其放入您的项目文件夹中。
2.然后在.m文件中#import“NSAttributedString+Attributes.h”。
3.现在您可以更改字符串颜色、字体、大小等,如下所示。
https://github.com/AliSoftware/OHAttributedLabel
1.Above is a link 4 files from github which u download and place it in your project folder.
2.Then #import "NSAttributedString+Attributes.h" in you .m file.
3.Now u can change your string color, font, size etc. like below.