如何分配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吗?

NSString只是一个字符串。它没有颜色、字体、粗细、大小、样式或任何东西——只有字符。你会想要使用NSAttributedString。

但是请记住NSAttributedString不是一个NSString——它基本上是一个轻量级容器,它将字符串与属性字典配对,并提供适当的绘图代码。特别是,你不能将NSAttributedString传递给期望字符串的API。你要么有一个接受NSAttributedString的API要么自己绘制字符串

你不能给字符串指定颜色。字符串没有关于颜色的数据。您可以为标签指定颜色,如

cell.textLabel.textColor = [UIColor grayColor];

必须等到显示字符串时才能设置颜色。如果需要,您可以将颜色存储在UIColor *类型的变量中,以便稍后使用。

你不能在字符串上设置颜色,你可以在标签上设置颜色。字符串只是一个字符序列-标签负责显示它,因此控制诸如颜色之类的东西。

查看UILabel类引用并查找textColor属性

在你的例子中,我认为你应该:

cell.textLabel.textColor = [UIColor grayColor];

https://github.com/AliSoftware/OHAttributedLabel

1。以上是你从github下载的4个文件的链接,并将其放在你的项目文件夹中。

2。然后#import "NSAttributedString+Attributes.h"到你的。m文件中。

3。现在你可以改变你的字符串颜色,字体,大小等如下。

NSString *prev = @"Name: ";
NSMutableAttributedString *now = [NSMutableAttributedString  attributedStringWithString:prev];
[now setTextColor:[UIColor blueColor]];
[now setFont:[UIFont fontWithName:@"AppleGothic" size:24]];

最新更新