改变" label.text"的颜色范围

时间:2014-04-22 03:32:02

标签: ios nsmutableattributedstring

iOS7 addAttribute:(NSString *)NSForegroundColorAttributeName value:可以更改label.text颜色 但在iOS6中会崩溃

iOS6 addAttribute:(NSString *)kCTForegroundColorAttributeName value:无法更改label.text.color

我该怎么办?

- (void)userNoPayCreateFreeLabel
{
    UILabel *freeLabel = [[UILabel alloc] initWithFrame:CGRectMake(
                                                        0,
                                                        NAVIGATIONBAR_HEIGHT,
                                                        self.view.bounds.size.width,
                                                        28)];
    NSString *text = @"购买课程将享有高质量答疑,你可免费体验3次";
    freeLabel.attributedText = [self changeLableTextColorStr:text];
    freeLabel.backgroundColor = [CommUtls colorWithHexString:@"#fdfbf1"];
    freeLabel.font = [UIFont systemFontOfSize:13];
    freeLabel.textAlignment = 1;
    self.freeLabel = freeLabel;
    [self.view addSubview:freeLabel];
}

- (NSMutableAttributedString *)changeLableTextColorStr:(NSString *)text
{
    NSMutableAttributedString *aStr = [[NSMutableAttributedString alloc] initWithString:text];
    NSRange range = NSMakeRange([aStr length] - 2, 1);
    if (IsIOS7) {
        [aStr addAttribute:(NSString *)NSForegroundColorAttributeName value:
                                                (id)[UIColor redColor].CGColor range:range];
    }
    else {
        [aStr addAttribute:(NSString *)kCTForegroundColorAttributeName value:
                                                (id)[UIColor redColor].CGColor range:range];
    }
    return aStr;
}

1 个答案:

答案 0 :(得分:2)

试试这个,

[aStr addAttribute:NSStrokeColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, aStr.length)];
[aStr addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, aStr.length)];