微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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];

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐