iOS 简单的富文本

效果图:


     /** 
     NSMutableAttributedString类可以添加各种样式,常用的设置key有:
     NSForegroundColorAttributeName 设置前景色,也就是文本颜色
     NSFontAttributeName 设置字体
     NSBackgroundColorAttributeName 设置背景色
     */
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"蓝色的字,红色的背景,天蓝蓝,草绿绿,一片一片又一片"];
    
    [str addAttribute:NSForegroundColorAttributeName
                value:[UIColor blueColor]
                range:NSMakeRange(0,10)];
    [str addAttribute:NSBackgroundColorAttributeName
                value:[UIColor redColor]
                range:NSMakeRange(0, 10)];
    [str addAttribute:NSForegroundColorAttributeName
                value:[UIColor cyanColor]
                range:NSMakeRange(11,12)];
    [str addAttribute:NSForegroundColorAttributeName
                value:[UIColor greenColor]
                range:NSMakeRange(19,6)];
    [str addAttribute:NSFontAttributeName
                value:[UIFont fontWithName:@"Arial" size:30.0]
                range:NSMakeRange(0, 10)];
    [str addAttribute:NSFontAttributeName
                value:[UIFont fontWithName:@"Arial" size:12.0]
                range:NSMakeRange(11, 12)];
    [str addAttribute:NSFontAttributeName
                value:[UIFont fontWithName:@"Arial" size:30.0]
                range:NSMakeRange(19, 6)];
    
    UILabel *attrLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 150, 320 - 40, 120)];
    attrLabel.attributedText = str;  
    attrLabel.numberOfLines = 0;
    
    [self.view addSubview:attrLabel];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容