使用NSAttributed String更改字符串的颜色和字体

tec*_*man 21 objective-c nsattributedstring addattribute ios

我有一个字符串,其中最后一个单词与整个字符串中的其他单词相比总是具有不同的颜色,例如:如果字符串颜色为黑色,则语句中的最后一个单词将为红色.我正在使用NSAttributed字符串,如下所示:

NSDictionary *attrDict = [NSDictionary dictionaryWithObject:[UIFont fontWithName:Arial size:16.0] forKey:NSFontAttributeName];
NSMutableAttributedString *AattrString = [[NSMutableAttributedString alloc] initWithString:@"This is a" attributes: attrDict];
Run Code Online (Sandbox Code Playgroud)

我会为最后一个单词制作类似的NSAttributedString,并用第一个字符串修改它.

问题:我想在字符串中添加颜色和字体.我已经使用字典处理字体了.但是我可以在同一个字典中添加颜色处理程序/代码,或者在NSAttributedString上使用"addAttribute:"是添加颜色或任何其他属性的唯一方法吗?

rma*_*ddy 56

将颜色添加到与字体相同的字典中:

NSDictionary *attrDict = @{
    NSFontAttributeName : [UIFont fontWithName:Arial size:16.0],
    NSForegroundColorAttributeName : [UIColor redColor]
};
Run Code Online (Sandbox Code Playgroud)