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