我正在使用NSAttributedString
最好的结果。
- 更改上标文字的字体大小(使用
NSFontAttributeName
)。
- 向上移动上标文字(使用
NSBaselineOffsetAttributeName
)。
适用于所有类型的字体和所有sub/superscript的值。
//input parameters
NSString *title = @"e";
NSString *superscript = @"x";
UIFont *font = [UIFont systemFontOfSize:20.0f];
//our buffer
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
//just append the title and set its font
[attributedString appendString:title];
NSRange titleRange = NSMakeRange(0, title.length);
[attributedString addAttribute:NSFontAttributeName
value:font
range:titleRange];
//append the superscript
[attributedString appendString:superscript];
NSRange superscriptRange = NSMakeRange(title.length, superscript.length);
//start of the important code - change font and move baseline of the superscript
[attributedString addAttribute:NSFontAttributeName
value:[font fontWithSize:(font.pointSize/2.0f)]
range:superscriptRange];
[attributedString addAttribute:NSBaselineOffsetAttributeName
value:[NSNumber numberWithFloat:(font.ascender/2.0f)]
range:superscriptRange];
//end of the important code
[button setAttributedTitle:attributedString forState:UIControlStateNormal];
结果:
您发布的代码并没有试图有2²标签。你为什么不简单使用'@“2²”'? – rmaddy
@rmaddy,工作!谢谢! –