iOS - 富文本实现在UILabel中显示图片

	UILabel *messageLabel = [[UILabel alloc] init];
    
    //创建富文本
    NSMutableAttributedString *messageStr = [[NSMutableAttributedString alloc] init];
    
    //NSTextAttachment可以将要插入的图片作为特殊字符处理
    NSTextAttachment *messageAttach = [[NSTextAttachment alloc] init];
    //定义图片内容及位置和大小
    messageAttach.image = [UIImage imageNamed:@"message.png"];
    //messageAttach.bounds = CGRectMake(0, 0, 61, 14);
    //创建带有图片的富文本
    NSAttributedString *messageImageStr = [NSAttributedString attributedStringWithAttachment:messageAttach];
    [messageStr appendAttributedString:messageImageStr];
    
    //富文本中的文字
    NSString *messageText = @"  富文本显示图片";
    NSAttributedString *messageTextStr = [[NSAttributedString alloc] initWithString:messageText attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:KCBlackColor}];
    [messageStr appendAttributedString:messageTextStr];
    
    //用label的attributedText属性来使用富文本
    messageLabel.attributedText = messageStr;
    [self.view addSubview:messageLabel];
    [messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.bottom.equalTo(self.view.mas_bottom).offset(-89 * ratio);
    }];

参考:http://www.cnblogs.com/Apologize/p/5908503.html

你可能感兴趣的:(IOS开发)