属性字符串添加图片

- (NSMutableAttributedString *)getAttributedStringWithSting:(NSString *)astring image:(UIImage *)image index:(NSInteger)index{
        // 1.创建一个富文本
    NSMutableAttributedString *attri =  [[NSMutableAttributedString alloc] initWithString:astring];
    
//        // 修改富文本中的不同文字的样式
//    [attri addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, 5)];
//    [attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, 5)];
//
//        // 设置数字为红色
//    [attri addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(5, 9)];
//    [attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:NSMakeRange(5, 9)];
    
        // 2.添加表情图片
    NSTextAttachment *attch = [[NSTextAttachment alloc] init];
        // 表情图片
    attch.image = image;
        // 设置图片大小
    attch.bounds = CGRectMake(0, -3, 16, 16);
    
        // 创建带有图片的富文本
    NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
    [attri insertAttributedString:string atIndex:index];// 插入某个位置
    
    return attri;
}

posted @ 2018-05-16 09:54  弋小木  阅读(289)  评论(0编辑  收藏  举报