xi.lin xi.lin - 1 month ago 5
iOS Question

Setting vertical align of truncated tails for NSAttributedString with NSTextAttachment

I'm using the following code to generate a

NSAttributedString
for
UILabel
in iOS 8.

// a long long Chinese title
NSString *title = @"这是一个很长很长很长很长很长很长的中文标题";
// setup icon attachment
NSTextAttachment *iconAttachment = [[NSTextAttachment alloc] init];
iconAttachment.image = [UIImage imageNamed:imageName];
iconAttachment.bounds = bounds;
NSAttributedString *ycardImageString = [NSAttributedString attributedStringWithAttachment:iconAttachment];

// setup attributed text
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:title];
if (shouldShowYcard) {
[attributedText insertAttributedString:ycardImageString atIndex:0];
[attributedText insertAttributedString:[[NSAttributedString alloc] initWithString:@" "] atIndex:1];
[attributedText addAttribute:NSBaselineOffsetAttributeName value:@(offset) range:NSMakeRange(0, 1)];
}
NSRange titleRange = NSMakeRange(shouldShowYcard ? 2 : 0, title.length);
[attributedText addAttribute:NSFontAttributeName value:font range:titleRange];
[attributedText addAttribute:NSForegroundColorAttributeName value:color range:titleRange];


However it seems that the
NSTextAttachment
will effect the vertical position of truncated tails, just like the following pictures.

NSAttributedString with NSTextAttachment
NSAttributedString without NSTextAttachment
NSAttributedString with NSTextAttachment In English
NSAttributedString without NSTextAttachment In English

Is there a way to set the vertical aignment for the truncated tails?

My goal is to have bottom align tails in Chinese language.

This is an icon for test.icon

Answer

OK, finally I choose a ugly way to fix this problem by setting NSBaselineOffsetAttributeName for truncate tail.

Here is a way to calculate the truncate part. But in my case, my label width is fixed so that I can directly set the range for control.

if (title.length > 10 && ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)) {
    [attributedText addAttribute:NSBaselineOffsetAttributeName value:@(-4) range:NSMakeRange(9, 1)];
}