zoukankan      html  css  js  c++  java
  • iOS

    代码如下

    
       NSMutableAttributedString *hintString=[[NSMutableAttributedString alloc]initWithString:@"(故障)"];
            NSRange range1=[[hintString string]rangeOfString:@"()"];
            [hintString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:range1];
            NSRange range2=[[hintString string]rangeOfString:@"故障"];
            [hintString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range2];
            //下面是需要给哪个lable进行赋值
            self.lblDpfStatus.attributedText = hintString;
    
    

    封装成工具类

    
    #import <UIKit/UIKit.h>
    @interface NSObject (Tool)
    
    -(NSAttributedString *)setString:(NSString *)str withColorOneStr:(NSString *)oneStr andColorOne:(UIColor *)colorOne andColorTwoStr:(NSString *)twoStr andColorTwo:(UIColor *)colorTwo;
    
    @end
    
    //.m文件中
    
    #import "NSObject+Tool.h"
    
    @implementation NSObject (Tool)
    
    -(NSAttributedString *)setString:(NSString *)str withColorOneStr:(NSString *)oneStr andColorOne:(UIColor *)colorOne andColorTwoStr:(NSString *)twoStr andColorTwo:(UIColor *)colorTwo{
        
        NSMutableAttributedString *hintString=[[NSMutableAttributedString alloc]initWithString:str];
        NSRange range1=[[hintString string]rangeOfString:oneStr];
        [hintString addAttribute:NSForegroundColorAttributeName value:colorOne range:range1];
        NSRange range2=[[hintString string]rangeOfString:twoStr];
        [hintString addAttribute:NSForegroundColorAttributeName value:colorTwo range:range2];
        return hintString;
    }
    
    @end
    
    

    测试工具类

    
    - (void)viewDidLoad {
        
        [super viewDidLoad];
        UILabel * lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 100, 35)];
        lbl.text = @"hello world";
        lbl.attributedText = [self setString:lbl.text withColorOneStr:@"hello" andColorOne:[UIColor orangeColor] andColorTwoStr:@"w" andColorTwo:[UIColor redColor]];
        [self.view addSubview:lbl];
    }
    
    

    测试结果如下

    设置的字符串必须是连续的否则无效如图

  • 相关阅读:
    [置顶] 利用CXF发布webService的小demo
    【转】VirtualBox下Ubuntu共享文件
    【转】你应该知道的十个VirtualBox技巧与高级特性
    【转】ubuntu 12.04英文版设置成中文版
    【转】Ubuntu安装基础教程
    【转】Ubuntu更改语言环境设置
    【转】【教程】实现Virtualbox中的XP虚拟机和主机Win7之间的共享文件夹
    【转】VIRTUALBOX导入已有.VDI文件步骤
    winhex的使用
    【转】VC MFC 如何删除文件,目录,文件夹
  • 原文地址:https://www.cnblogs.com/adampei-bobo/p/6292930.html
Copyright © 2011-2022 走看看