zoukankan      html  css  js  c++  java
  • 将且仅将UILabel上的所有数字变色指定的字体颜色<转>

    先提出一个场景,一个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;

  • 相关阅读:
    关于在pycharm下提示ModuleNotFoundError: No module named 'XXX' 的一种可能
    记录Python类与继承的一个错误
    JavaScript 中this 初步理解笔记
    Kibana6.x.x源码分析--如何自定义savedObjectType对象
    Kibana6.x.x源码分析--如何使用kibana的savedObjectType对象
    AngularJs依赖注入写法笔记
    Kibana6.x.x源码分析--ngReact使用
    Kibana6.x.x源码分析--Error: $injector:nomod Module Unavailable
    互联网时代,我们可以选择不做穷人
    ES6问题记录--Promise
  • 原文地址:https://www.cnblogs.com/deng37s/p/6912712.html
Copyright © 2011-2022 走看看