我正在使用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,工作!謝謝! –