调整范围基线的NSAttributedString不能按预期在UILabel中工作

时间:2015-04-15 08:27:41

标签: ios objective-c uilabel nsattributedstring core-text

我正在尝试调整属性字符串的一部分的基线

UILabel *detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(cell.contentView.bounds.size.width-100, 0, 75, cell.contentView.bounds.size.height)];
[cell.contentView addSubview:detailLabel];
detailLabel.textAlignment = NSTextAlignmentRight;

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"5" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Thin" size:18]}];
NSAttributedString *subScript = [[NSAttributedString alloc] initWithString:@"b" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Thin" size:18],
                                                                                                (NSString *)kCTSuperscriptAttributeName: @(-2)}];
[attributedString appendAttributedString:subScript];


cell.attributedText = attributedString;

但所有文字都经过调整,而不仅仅是被归属的部分

我尝试使用UILabel's baselineAdjustment属性,但没有看到任何差异

以下是属性字符串说明

Printing description of attributedString:
5{
    NSFont = "<UICTFont: 0x7fbde0d548a0> font-family: \"HelveticaNeue-Thin\"; font-weight: normal; font-style: normal; font-size: 18.00pt";
}b{
    NSFont = "<UICTFont: 0x7fbde0d548a0> font-family: \"HelveticaNeue-Thin\"; font-weight: normal; font-style: normal; font-size: 18.00pt";
    NSSuperScript = "-2";
}
(lldb) 

这是可见的结果

Print screen from the simulator

调试视图层次结构中的图像

Debug print screen

1 个答案:

答案 0 :(得分:0)

这可以通过这种排版技巧来完成:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"5" attributes:@{
    NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Thin" size:18],
}];
[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@" " attributes:@{
    NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Thin" size:18],
    (NSString *)kCTSuperscriptAttributeName: @2,
    NSKernAttributeName: @-5,
}]];
[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"b" attributes:@{
    NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Thin" size:18],
    (NSString *)kCTSuperscriptAttributeName: @-2,
}]];

这里发生了什么:

  1. 在&#34; 5&#34;之间添加空格字符和&#34; b&#34;使用与&#34; b&#34;。
  2. 相同的字体
  3. 从&#34; b&#34;向相反方向移动该空间转移,并具有相同的价值。现在&#34; 5 b&#34;字符串增加&#34;空格&#34;等于&#34; b&#34;增加等量下。 UILabel将对齐生成的字符串和&#34; 5&#34;将是死亡中心。
  4. 视觉上转移&#34; b&#34;到&#34; 5&#34;通过应用否定字距调整。