NSMutableAttribute 使用注意点

2017-11-06  本文已影响17人  西边雨

前些天,使用NSMutableAttribute 设置不同的字体大小和颜色, 突然发现了一个小坑。

由于需求的问题,需要定时更新字符串。 导致下面的坑出现了。

先不说, 先来看看代码

  UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 400, self.view.bounds.size.width, 50)];
    label.textColor = [UIColor blueColor];
    for (int i = 0 ; i < 5; i++) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * (i+1) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            //NSMutableAttributedString 如果对没有设置字体的颜色 是什么颜色呢?
            NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:@"黑色红色1默认颜色" attributes:@{NSForegroundColorAttributeName:label.textColor}];
            [attributeString setAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]} range:NSMakeRange(0, 2)];
            [attributeString setAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} range:NSMakeRange(2, 3)];
            label.attributedText = attributeString;
            
        });
    }
    [self.view addSubview:label];]

在循环第一次的时候,显示没有问题。

image.png

在第二次循环到时候,就出现了错误,默认的颜色不是蓝色,而是黑色。

image.png

经过定位发现,AttributeText使用了label.textColor, 每次设置了AttributeText的时候,label的textColor颜色都会被修改为AttributeText的第一个字的颜色。

上一篇 下一篇

猜你喜欢

热点阅读