ios 使用 NSAttributed String 更改字符串的颜色和字体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19309484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change color and font of a string using NSAttributed String
提问by tech_human
I have a string in which last word would always be of a different color compared to the other words in entire string eg: if the string color is black then last word in the statement would be of red color. I am using NSAttributed string for it as below:
我有一个字符串,其中最后一个单词与整个字符串中的其他单词相比总是具有不同的颜色,例如:如果字符串颜色为黑色,则语句中的最后一个单词将为红色。我正在使用 NSAttributed 字符串,如下所示:
NSDictionary *attrDict = [NSDictionary dictionaryWithObject:[UIFont fontWithName:Arial size:16.0] forKey:NSFontAttributeName];
NSMutableAttributedString *AattrString = [[NSMutableAttributedString alloc] initWithString:@"This is a" attributes: attrDict];
I would be making similar NSAttributedString for the last word and will the amend it with first string.
我会为最后一个单词制作类似的 NSAttributedString 并将用第一个字符串修改它。
Question:I want to add color to the string along with the font. I am already handling the font using dictionary. But can I add the color handler/code in the same dictionary or using "addAttribute:" on NSAttributedString is the only other way to add color or any other attributes?
问题:我想将颜色与字体一起添加到字符串中。我已经在使用字典处理字体。但是我可以在同一个字典中添加颜色处理程序/代码,或者在 NSAttributedString 上使用“addAttribute:”是添加颜色或任何其他属性的唯一其他方法吗?
回答by rmaddy
Add the color to the same dictionary as the font:
将颜色添加到与字体相同的字典中:
NSDictionary *attrDict = @{
NSFontAttributeName : [UIFont fontWithName:Arial size:16.0],
NSForegroundColorAttributeName : [UIColor redColor]
};