使用NSTextAttachment为NSAttributedString设置截断尾部的垂直对齐

xi.*_*lin 8 alignment nsattributedstring uilabel nstextattachment ios

我正在使用以下代码在iOS 8中生成NSAttributedStringfor UILabel.

// 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];
Run Code Online (Sandbox Code Playgroud)

然而,似乎NSTextAttachment会影响截断尾部的垂直位置,就像下面的图片一样.

带有NSTextAttachment的NSAttributedString 没有NSTextAttachment的NSAttributedString 带有NSTextAttachment的NSAttributedString英文版 没有NSTextAttachment的NSAttributedString英文版

有没有办法为截断的尾部设置垂直对齐?

我的目标是用中文底部对齐尾部.

这是一个测试图标.图标

xi.*_*lin 0

好吧,最后我选择了一个丑陋的方法来解决这个问题,即设置NSBaselineOffsetAttributeName截尾。

是计算截断部分的方法。但就我而言,我的标签宽度是固定的,因此我可以直接设置控制范围。

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