如何在uilabel中为字母设置不同的颜色

时间:2015-09-14 09:32:50

标签: ios objective-c iphone uilabel nsmutableattributedstring

我想在uilabel中为字母设置灰色。如何在NSMutableAttributedString中设置范围值。

示例:

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:@"1.2 Sun - 3.4 Mon"];
[attrString beginEditing];
[attrString addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range: ]; // how to set range here for alphabets
[attrString endEditing];

1 个答案:

答案 0 :(得分:0)

试试这个。

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:@"1.2 Sun - 3.4 Mon"];

if([[attrString string] rangeOfString:@"Sun"].location != NSNotFound)
{
     NSRange range2 = [[attrString string] rangeOfString:@"Sun"];

    [attrString addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:range2];
}

if([[attrString string] rangeOfString:@"Mon"].location != NSNotFound)
{
    NSRange range2 = [[attrString string] rangeOfString:@"Mon"];

    [attrString addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:range2];
}

快乐编码:)