9

before

I want to align the NSTextAttachment to the center of the text, so I set NSBaselineOffsetAttributeName to change the baseline of NSTextAttachment.

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:@"" attributes:@{NSFontAttributeName: [UIFont fontWithName:@"STHeitiSC-Light" size:17]}];
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"micon"];        
NSMutableAttributedString *ats = [[NSAttributedString attributedStringWithAttachment:attachment] mutableCopy];
[ats addAttributes:@{NSBaselineOffsetAttributeName:@(-5),NSFontAttributeName: [UIFont fontWithName:@"STHeitiSC-Light" size:17]} range:(NSRange){0,ats.length}];
[attrString appendAttributedString:s];

Then I calculate the size for UILabel and set attributedText.

CGRect textFrame = [attrString boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil];
UILabel *label = [[UILabel alloc] initWithFrame:textFrame];
label.lineBreakMode = NSLineBreakByCharWrapping;
label.numberOfLines = 0;
label.attributedText = attributed;
label.backgroundColor = [UIColor clearColor];

Finally the last image disappeared.

after

Can anyone explain why this is happening and how to fix it.

drinking
  • 1,533
  • 3
  • 15
  • 22
  • 1
    Hi fallow this link its very helpfull you http://stackoverflow.com/questions/26105803/center-nstextattachment-image-next-to-single-line-uilabel – Vinayak Mar 30 '16 at 12:49

1 Answers1

6

I finally solve it by adding another attribute NSParagraphStyleAttributeName

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.minimumLineHeight = lineheight; //line height equals to image height
    [attributes setValue:paragraphStyle forKey:NSParagraphStyleAttributeName];

don't change the image's offset, just set the text's offset.

drinking
  • 1,533
  • 3
  • 15
  • 22