在NSAttributedString中垂直放置两个不同大小的字体

我使用NSAttributedString生成两个不同大小的string。 但是默认情况下,它的底部alignment如下所示:

基线对齐大小

但是我想垂直居中,像这样: 垂直居中尺寸

要清楚,这是一个单一的属性string,不是两个或更多。 这是一个简单的例子来描述我的问题,我实际上想要做的更复杂。

我会说最简单的事情就是操纵有问题的文本的NSBaselineOffsetAttributeName属性:

NSBaselineOffsetAttributeName

此属性的值是一个NSNumber对象,其中包含一个浮点值,用于指示该字符与基线的偏移量(以磅为单位)。 默认值是0。

为了居中,您需要将大文本的高度和较小文本的高度之间的差异减半,然后将其用作基线调整。

这是一个使用NSBaselineOffsetAttributeName垂直alignment较小文本的工作示例。

 NSString *bigString = @"BIG"; NSString *smallString = @"Small String"; NSString *fullString = [NSString stringWithFormat:@"%@ %@", bigString, smallString]; NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:fullString]; NSRange bigStringRange = NSMakeRange(0, bigString.length); NSRange smallStringRange = NSMakeRange(bigStringRange.length, smallString.length); [string beginEditing]; //Set big string font and size [string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:28.0] range:bigStringRange]; //set small string font and size [string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18.0] range:smallStringRange]; //Set small string baseline offset [string addAttribute:NSBaselineOffsetAttributeName value:[NSNumber numberWithFloat:3.0] //adjust this number till text appears to be centered range:smallStringRange]; [string endEditing]; 

更好的解决scheme是从字体排版计算NSBaselineOffsetAttributeName(简短的文章https://www.raizlabs.com/dev/2015/08/advanced-ios-typography/

为属性string的第二部分设置属性。

 secondPartAttributes[NSBaselineOffsetAttributeName] = @((firstFont.xHeight - secondFont.xHeight)/2);