富文本

  • NSTextAttachment:图片转化成富文本内容
  • NSAttributedString:文字的富文本
  • NSMutableAttributedString:可变的富文本,就可以把内容和文字转好的富文本添加进来成为图文混排。

[TOC]

示例1:文字字体颜色定制

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UILabel *attrLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 创建NSAttributedString对象
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:@"Talk is cheap, show me the code"];
    // 设置前半部分为红色
    NSRange PrefixRange = [attrStr.string rangeOfString:@"Talk is cheap"];
    [attrStr setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName : [UIFont boldSystemFontOfSize:20]} range:PrefixRange];
    // 设置后半部分背景为紫色
    NSRange lastRange = [attrStr.string rangeOfString:@"show me the code"];
    [attrStr setAttributes:@{NSBackgroundColorAttributeName : [UIColor purpleColor], NSForegroundColorAttributeName : [UIColor greenColor]} range:lastRange];
    
    
    self.attrLabel.attributedText = attrStr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

示例2:图文混排

不可编译 调用

调用:  NSAttributedString *downloadAttr = [self createAttrStringWithText:model.downloads image:[UIImage imageNamed:@"topic_Download"]];
    _downLoadLabel.attributedText = downloadAttr;

// 创建图文混排的富文本
// CoreText.framework 图文混排框架
- (NSAttributedString *) createAttrStringWithText:(NSString *) text image:(UIImage *) image
{
    // NSTextAttach 可以将图片转换为富文本内容
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    // 创建通过NSTextAttachment的富文本
    // 图片的富文本
    attachment.image = image;
    // 文字的富文本
    NSAttributedString *imageAttr = [NSAttributedString attributedStringWithAttachment:attachment];
    NSAttributedString *textAttr = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13]}];
    NSMutableAttributedString *mutableAttr = [[NSMutableAttributedString alloc] init];
    [mutableAttr appendAttributedString:imageAttr];
    [mutableAttr appendAttributedString:textAttr];
    // copy出来是不可变的
    return [mutableAttr copy];
}

你可能感兴趣的:(富文本)