码迷,mamicode.com
首页 > 其他好文 > 详细

将且仅将UILabel上的所有数字变色指定的字体颜色<转>

时间:2017-05-27 15:16:42      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:font   under   attribute   bst   make   obj   lin   ext   name   

先提出一个场景,一个UILabel上面有各种数字字符中文字符以及字母等,现在我们想将其中的数字找出来并且变为和其他字符不同的颜色。 这里提出一个解决方法,通过for循环来截取一个一个字符,判断其是不是0-9的数字,如果是就设置他的字体属性,我们使用了 NSMutableAttributedString实现富文本(带属性的字符串)。 NSAttributedString的使用方法,跟NSMutableString,NSString类似 1.使用方法: 为某一范围内文字设置多个属性 - (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range; 为某一范围内文字添加某个属性 - (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range; 为某一范围内文字添加多个属性 - (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range; 移除某范围内的某个属性 - (void)removeAttribute:(NSString *)name range:(NSRange)range; 2. 常见的属性及说明 NSFontAttributeName 字体 NSParagraphStyleAttributeName 段落格式 NSForegroundColorAttributeName 字体颜色 NSBackgroundColorAttributeName 背景颜色 NSStrikethroughStyleAttributeName删除线格式 NSUnderlineStyleAttributeName 下划线格式 NSStrokeColorAttributeName 删除线颜色 NSStrokeWidthAttributeName删除线宽度 NSShadowAttributeName 阴影 //PS:下划线属性的设置方法 //[attributeString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(i, 1)]; 那么进入正题!,首先我们创建好UILabel,然后通过for循环来查找符合条件的数字 @property (nonatomic,strong)UILabel *myLabel; self.myLabel = [[UILabelalloc]initWithFrame:CGRectMake(0,0, 375,100)]; self.myLabel.backgroundColor = [UIColorcyanColor];//天蓝色背景 self.myLabel.textAlignment =1;//居中 [self.viewaddSubview:self.myLabel]; //这是我们的测试用的文本字符串数据 NSString *content = @"abc123a1b2c3你懂得888"; NSArray *number = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"]; NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:content]; for (int i = 0; i < content.length; i ++) { //这里的小技巧,每次只截取一个字符的范围 NSString *a = [content substringWithRange:NSMakeRange(i, 1)]; //判断装有0-9的字符串的数字数组是否包含截取字符串出来的单个字符,从而筛选出符合要求的数字字符的范围NSMakeRange if ([number containsObject:a]) { [attributeString setAttributes:@{NSForegroundColorAttributeName:[UIColor blueColor],NSFontAttributeName:[UIFont systemFontOfSize:25],NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleSingle]} range:NSMakeRange(i, 1)]; } } //完成查找数字,最后将带有字体下划线的字符串显示在UILabel上 self.myLabel.attributedText = attributeString;

将且仅将UILabel上的所有数字变色指定的字体颜色<转>

标签:font   under   attribute   bst   make   obj   lin   ext   name   

原文地址:http://www.cnblogs.com/deng37s/p/6912712.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!