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.
Can anyone explain why this is happening and how to fix it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With