iOS富文本实例

效果图:

代码:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 300, 50)];

    lab.numberOfLines = 0;

    lab.text = @"朦朦胧胧萌萌哒:忽地萨发罗夫的送回国的萨可减肥经典款撒积分兑换可舒服了地方上课啦放假啊大家思考理发店说的就是咖喱惊魂甫定了件快乐的撒进防空洞酸辣粉了解到撒度撒化肥丹江口市啦大家看撒的环境撒发了大家看撒发的撒了咖啡店撒克拉的第撒对空射击啊。";

    lab.font = [UIFont systemFontOfSize:10];

    NSRange range = [lab.text rangeOfString:@":"];

    [self.view addSubview:lab];

    

    NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:lab.text];

    [att addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]}  range:NSMakeRange(0, range.location+1)];

    lab.attributedText = att;

    

    UILabel *lab1 = [[UILabel alloc] initWithFrame:CGRectMake(10, 80, 300, 20)];

    lab1.text = @"蹦蹦跳跳正在远离回复星星点灯追逐:好傻啊你";

    lab1.font = [UIFont systemFontOfSize:10];

    [self.view addSubview:lab1];

    

    NSRange range1 = [lab1.text rangeOfString:@"回复"];

    NSRange range2 = [lab1.text rangeOfString:@":"];

    NSMutableAttributedString *att1 = [[NSMutableAttributedString alloc] initWithString:lab1.text];

    [att1 addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]}  range:NSMakeRange(0, range1.location)];

    [att1 addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} range:NSMakeRange(range1.location+2, range2.location-range1.location-1)];

    NSLog(@"%d  %d",range1.location,range2.location);

    lab1.attributedText = att1;

}

@end

原文地址:https://www.cnblogs.com/wangbinios/p/6123968.html