NSAttributedString上标样式 [英] NSAttributedString superscript styling

查看:120
本文介绍了NSAttributedString上标样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个文本块中标注所有®字符的实例(法律免责声明,当然;)),默认方式 NSAttributedString 不是很好。

I want to superscript all the instances of ® character in a block of text (legal disclaimer, naturally ;)) and the default way NSAttributedString is not very good.

如果我只是让角色成为并且只使用未经修改的 NSString ,它将呈现与大写字母相同的大小并且大致位于基线处。如果我将superscript属性添加到 NSAttributedString ,如下所示:

If I just let the character be and only use unmodified NSString, it is rendered the same size as a capital letter and is placed approximately at the baseline. If I add the superscript attribute to NSAttributedString as follows:

[attrStr setAttributes:@{(NSString *)kCTSuperscriptAttributeName : @1} range:NSMakeRange(locationOfReg, 1)];

该字符从基线上抬起,其大小不变,但线间距现在受到影响,因为否则凸起的角色会侵入上面的那一行。

The character is lifted off the baseline, its size is unchanged, but the line spacing is now affected because the raised character would otherwise intrude on the line above.

举例说明:

我在Photoshop中创建了这个图像,通过减小角色的大小和移动来实现所需的位置基线。我知道如何在iOS中更改字体大小,但更改基线似乎更棘手。关于如何实现这一点的任何建议?

I created this image in Photoshop where the desired position was achieved by reducing the size of the character and shifting the baseline. I know how to change the font size in iOS, but changing the baseline seems trickier. Any suggestions on how to achieve this?

编辑:我想我可以使用上标属性作为一种方法来改变基线。现在最好找出一种获取当前字体大小的方法,然后减少它以允许在不同大小的文本块上使用相同的方法。

I suppose I could use the superscript attribute as a way to shift the baseline up. Now it would be great to figure out a way to get the current font size and subsequently reduce it to allow the same method to be used on blocks of text of different size.

推荐答案

以下代码似乎可以解决问题:

The following code seems to do the trick:

UIFont *fnt = [UIFont fontWithName:@"Helvetica" size:20.0];

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"GGG®GGG"
                                                                                     attributes:@{NSFontAttributeName: [fnt fontWithSize:20]}];
[attributedString setAttributes:@{NSFontAttributeName : [fnt fontWithSize:10]
                                  , NSBaselineOffsetAttributeName : @10} range:NSMakeRange(3, 1)];

这篇关于NSAttributedString上标样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆