iOS - UILabel添加图片之富文本的简单应用

时间:2024-04-24 10:04:43
//创建富文本
NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:@" -积分商城-热门商品-优惠券,后续会陆续打通东方明珠塔等各类上海文化消费优惠券。"];
//NSTextAttachment可以将要插入的图片作为特殊字符处理
NSTextAttachment *attch = [[NSTextAttachment alloc] init];
//定义图片内容及位置和大小
attch.image = [UIImage imageNamed:@"home_profile_icon"];
attch.bounds = CGRectMake(, , , );
//创建带有图片的富文本
NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch]; //将图片放在最后一位
//[attri appendAttributedString:string];
//将图片放在第一位
[attri insertAttributedString:string atIndex:];
//用label的attributedText属性来使用富文本
_imgLabel.attributedText = attri; //若想对图片添加点击事件,现在的想法是在label上添加一个透明按钮,位置大小跟图片的相同
_imgLabel.userInteractionEnabled = YES;
UIButton *clearBtn = [UIButton buttonWithType:UIButtonTypeCustom];
clearBtn.frame = CGRectMake(, , attch.bounds.size.width, attch.bounds.size.height+);
clearBtn.backgroundColor = [UIColor clearColor];
[clearBtn addTarget:self action:@selector(alertSth) forControlEvents:UIControlEventTouchUpInside];
[_imgLabel addSubview:clearBtn];