人猿星球

NSAttributedString 用法详解

2017-02-17  本文已影响93人  李小丫妮儿

关于一些属性的认知,每次都会被我们遗弃,每次都要百度,每次百度都是一大摊,总结一下NSAttributedString在工作中的基本用法。

1. 直接创建调用属性

#pragma 属性创建AttrbuteString
- (void)createAttrbuteString1{
//    1.创建
    NSMutableAttributedString *attributeStr1 = [[NSMutableAttributedString alloc] initWithString:_titleStr];
//    2.添加属性
    [attributeStr1 addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"AmericanTypewriter" size:17] range:NSMakeRange(0, _titleStr.length)];
    [attributeStr1 addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(0, 2)];
    [attributeStr1 addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(2, 5)];
    [attributeStr1 addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(8, 7)];
//    3.赋值
    _titleLabel.attributedText = attributeStr1;
}

运行如下效果:

AttributeStr1.png

2.创建属性字典

//    1.创建字典,添加每个需要的属性值
    NSDictionary *attDict1 = @{NSFontAttributeName:[UIFont fontWithName:@"AmericanTypewriter" size:17],NSForegroundColorAttributeName:[UIColor yellowColor]};
    NSAttributedString *attStr1 = [[NSAttributedString alloc] initWithString:[_titleStr substringWithRange:NSMakeRange(0, 2)] attributes:attDict1];
    
    NSDictionary *attDict2 = @{NSFontAttributeName:[UIFont fontWithName:@"AmericanTypewriter" size:17],NSForegroundColorAttributeName:[UIColor greenColor]};
    NSAttributedString *attStr2 = [[NSAttributedString alloc] initWithString:[_titleStr substringWithRange:NSMakeRange(2, 5)] attributes:attDict2];
    
    NSDictionary *attDict3 = @{NSFontAttributeName:[UIFont fontWithName:@"AmericanTypewriter" size:17],NSForegroundColorAttributeName:[UIColor blueColor]};
    NSAttributedString *attStr3 = [[NSAttributedString alloc] initWithString:[_titleStr substringWithRange:NSMakeRange(8, 7)] attributes:attDict3];
    
//    2.合并属性字典
    NSMutableAttributedString *totalAttStr = [[NSMutableAttributedString alloc] initWithAttributedString:attStr1];
    [totalAttStr appendAttributedString:attStr2];
    [totalAttStr appendAttributedString:attStr3];
    
//    3.赋值
    _titleLabel.attributedText = totalAttStr;
}

效果如下:

AttributeStr2.png

** 两种创建方式一样。。。择优选择 **

3.其他属性说明

** AttributedString 一共有21个属性,用的时候直接赋值就好,总结如下:*

  • NSFontAttributeName:设置字体属性,默认值:字体:Helvetica(Neue) 字号:12
上一篇下一篇

猜你喜欢

热点阅读