Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Why do NSTextAttachment disappear when setting NSBaselineOffsetAttributeName?

Tags:

ios

iphone

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.

like image 734
drinking Avatar asked Sep 11 '14 10:09

drinking


1 Answers

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.

like image 175
drinking Avatar answered Sep 28 '22 18:09

drinking