首页 > 代码库 > NSMutableAttributedString简单使用
NSMutableAttributedString简单使用
1、
//运行效果
self.attributeStringLabel.attributedText = [self getAttributedStringWithString:@"富为本属性字体" aString:@"颜色" aString:@"下划线"];
/**
* NSMutableAttributedString 简单使用demo方法
*
* @param str1 第一个属性字符串
* @param str2 第一个属性字符串
* @param str3 第一个属性字符串
*
* @return NSMutableAttributedString
*/
- (NSMutableAttributedString *)getAttributedStringWithString:(NSString *)str1 aString:(NSString *)str2 aString:(NSString *)str3{
NSString *normalString = [NSString stringWithFormat:@"%@--%@--%@", str1, str2, str3];
NSMutableAttributedString *attritedString = [[[NSMutableAttributedString alloc] initWithString:normalString] autorelease];
//每个属性的NSRange
NSRange range1 = [normalString rangeOfString:str1];
NSRange range2 = [normalString rangeOfString:str2];
NSRange range3 = [normalString rangeOfString:str3];
//每个NSRange里的具体属性(所有属性可以到UIKit框架里面的NSAttributedString查询)
NSDictionary *attrites1 = [NSDictionary dictionaryWithObject:[UIFont fontWithName:@"Palatino-Roman" size:20.0f] forKey:NSFontAttributeName];
NSDictionary *attrites2 = [NSDictionary dictionaryWithObject:[UIColor purpleColor] forKey:NSForegroundColorAttributeName];
NSDictionary *attrites3 = [NSDictionary dictionaryWithObject:[UIColor redColor] forKey:NSUnderlineColorAttributeName];
NSDictionary *attrites4 = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"1"] forKey:NSUnderlineStyleAttributeName];
//设置属性
[attritedString addAttributes:attrites1 range:range1];
[attritedString addAttributes:attrites2 range:range2];
[attritedString addAttributes:attrites3 range:range3];
[attritedString addAttributes:attrites4 range:range3];
return attritedString;
}
2、iOS7以后新添加了API可以通过URL和流来过的富文本
NSMutableAttributedString *attritedString1 = [[NSMutableAttributedString alloc] initWithFileURL:<#(NSURL *)#> options:<#(NSDictionary *)#> documentAttributes:<#(NSDictionary **)#> error:<#(NSError **)#>]
NSMutableAttributedString *attritedString2 = [NSMutableAttributedString alloc] initWithData:<#(NSData *)#> options:<#(NSDictionary *)#> documentAttributes:<#(NSDictionary **)#> error:<#(NSError **)#>;