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

将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富文本添加图片并设置居中)