这个就是一个简单的NSString改变为NSAttributedString后
对字符串进行rang查找和颜色替换。
直接上代码。
- (NSAttributedString *)transformString:(NSString *)string{
NSMutableAttributedString *textColor = [[NSMutableAttributedString alloc]initWithString:string];
[textColor addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:NSMakeRange(0, string.length)];
[textColor addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, string.length)];
if ([string containsString:@"天"]) {
NSRange range = [string rangeOfString:@"天"];
[textColor addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:range];
[textColor addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:range];
}
if ([string containsString:@"时"]) {
NSRange range = [string rangeOfString:@"时"];
[textColor addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:range];
[textColor addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:range];
}
if ([string containsString:@"分"]) {
NSRange range = [string rangeOfString:@"分"];
[textColor addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:range];
[textColor addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:range];
}
if ([string containsString:@"秒"]) {
NSRange range = [string rangeOfString:@"秒"];
[textColor addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:range];
[textColor addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:range];
}
return textColor;
}
本文介绍了一种使用Objective-C编程语言将简单的NSString转换为NSAttributedString的方法,并演示了如何通过查找特定字符串并更改其颜色和字体大小来实现文本的个性化显示。
1万+

被折叠的 条评论
为什么被折叠?



