美文网首页OC-开发案例收集iOS常用很常
iOS UILabel富文本添加图片并设置居中

iOS UILabel富文本添加图片并设置居中

作者: StevenHu_Sir | 来源:发表于2021-03-20 22:20 被阅读0次

将NSTextAttachment图像居中于单行UILabel旁边

1.效果图

image.png

2.代码实现

_titleLabel = [UILabel hk_labelWithFrame:CGRectMake(_avatarImageV.hk_right + 10.5 *xbScale, 22.5 * xbScale, 200*xbScale, 20*xbScale) font:HKBoldFont(15) color:HKHexString(@"#3B3B3B") content:@"小月月"];
//    _titleLabel.backgroundColor = HKRed;
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]initWithString:@"小月月"];
    [attrStr addAttribute:NSFontAttributeName value:HKBoldFont(15) range:NSMakeRange(0, [@"小月月" length])];
    NSTextAttachment *icon = [[NSTextAttachment alloc] init];
    UIImage *iconImage = [UIImage imageNamed:@"icon_goddness_top"];
    [icon setBounds:CGRectMake(0, roundf(HKBoldFont(15).capHeight - iconImage.size.height)/2.f, iconImage.size.width, iconImage.size.height)];
    [icon setImage:iconImage];
    NSAttributedString *iconString = [NSAttributedString attributedStringWithAttachment:icon];
    [attrStr appendAttributedString:iconString];

    _titleLabel.attributedText = attrStr;
    [self.contentView addSubview:_titleLabel];

相关文章

网友评论

    本文标题:iOS UILabel富文本添加图片并设置居中

    本文链接:https://www.haomeiwen.com/subject/dhsgcltx.html