美文网首页
一个Label显示两种颜色(iOS)

一个Label显示两种颜色(iOS)

作者: 布呐呐u | 来源:发表于2019-07-26 14:43 被阅读0次

    1)效果展示

    屏幕快照 2019-07-26 下午2.37.20.png

    2)源码分享

    - (UILabel *)targetLabelWithTitle:(NSString *)title{
    
           UILabel *label  = [[UILabel alloc]init];
           label.frame     = CGRectMake(0,self.view.frame.size.height /2, self.view.frame.size.width, 100);
    
           label.textColor = [UIColor orangeColor];
           label.textAlignment = NSTextAlignmentCenter;
           label.font          = [UIFont boldSystemFontOfSize:30.0f];
    
           NSRange startRange = [title rangeOfString:@"("];
           NSRange endRange   = [title rangeOfString:@")"];
           NSRange range      = NSMakeRange(startRange.location + startRange.length,endRange.location - (startRange.location + startRange.length));
           NSString *beforeString   = [title substringToIndex:startRange.location];
           NSString *resultString   = [title substringWithRange:range];
    
           //重置去掉"()"后的title
           NSString *handleString   = [NSString stringWithFormat:@"%@%@",beforeString,resultString];
    
           NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:handleString];
           NSRange resultRange = NSMakeRange([[attributedString string] rangeOfString:resultString].location, [[attributedString string] rangeOfString:resultString].length);
           //需要的特殊颜色
           [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:resultRange];
           //设置属性字符串
           label.attributedText = attributedString;
    
           return label;
    }
    

    3)使用方法

    • ① 在你需要的地方创建Label;

    • ② 传入带括号的(字符串)

    • ③ 括号内的文字就是需要改变的目标颜色

      UILabel *l  = [self targetLabelWithTitle:@"啊哈哈哈(想不到吧)"];
      [self.view addSubview:l];

    相关文章

      网友评论

          本文标题:一个Label显示两种颜色(iOS)

          本文链接:https://www.haomeiwen.com/subject/tozrrctx.html