如何将 uilabel 图标与 iOS 中的文本对齐

How to align uilabel icon with text in iOS

我使用以下代码将图标添加到我的 UILabel

        UIImage *image3 = [UIImage imageNamed:@"icon_comments.png"];

        UIImage *myIcon3 = [self imageWithImage:image3 scaledToSize:CGSizeMake(20, 20)];
        NSTextAttachment *attachment3 = [[NSTextAttachment alloc] init];
        attachment3.image = myIcon3;


        NSAttributedString *attachmentString3 = [NSAttributedString attributedStringWithAttachment:attachment3];
        NSString *temp3 = [NSString stringWithFormat: @"%d", test.noComments];
        NSAttributedString *titleString3 = [[NSAttributedString alloc] initWithString:temp3];

        NSMutableAttributedString *myString3 = [[NSMutableAttributedString alloc] initWithString:@""];
        [myString3 appendAttributedString:attachmentString3];
        [myString3 appendAttributedString:titleString3];


        cell.noComments.attributedText = myString3;

现在的问题是文本没有与图标垂直对齐,谁能告诉我这是什么问题,我该如何解决

您需要手动设置附件的边界以进行补偿。

CGFloat offsetY = //However much you need to offset the image + is down - is up
attachment3.bounds = CGRectMake(0, offsetY, myIcon3.size.width, myIcon3.size.height);

这适用于 iOS >= 7.0 对于某些 _label

NSRange range = [myString3.string rangeOfString:titleString3.string];
CGFloat dy = (_label.frame.size.height - _label.font.pointSize) / 2;
[myString3 addAttribute:NSBaselineOffsetAttributeName value:[NSNumber numberWithFloat:dy] range:range];

_label.attributedText = myString3;