label上同时显示文字和图片的富文本实现

2019-01-27  本文已影响5人  浪淘沙008

label上同时显示文字和图片的富文本实现

该方法实现于UILabel的category中,代码如下
- (void)attributeStrWithImage:(UIImage *)img withStr:(NSString *)str imgIndex:(NSInteger)index
{
    if (index > str.length) return;
    NSTextAttachment * imageAttachment = [[NSTextAttachment alloc] init];
    imageAttachment.image = img;
    imageAttachment.bounds = CGRectMake(0, -3, 12, 14);  //这行代码可以设置图片的位置和大小
    NSAttributedString * imageAttributedStr = [NSAttributedString attributedStringWithAttachment:imageAttachment];
    NSAttributedString * textAttributedStr = [[NSAttributedString alloc] initWithString:str];
    NSMutableAttributedString * attributedStr = [[NSMutableAttributedString alloc] initWithAttributedString:textAttributedStr];
    [attributedStr insertAttributedString:imageAttributedStr atIndex:index];
    self.attributedText =attributedStr;
}
上一篇 下一篇

猜你喜欢

热点阅读