Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

ios - NSAttributedString superscript styling

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.

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.

To illustrate:

variants of (R)

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?

Edit: 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)];

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...