我试图使用这个question创建一个标题为2平方的UIButton。但我无法让它工作。我错过了什么?
我的代码几乎完全相同:
if (button.tag == 200)
[button setTitle: @"x\u00B3 + x\u00B2 + x\u00B9 + k" forState: UIControlStateNormal | UIControlStateHighlighted | UIControlStateSelected];
提前致谢
答案 0 :(得分:2)
从iOS 6开始,您可以提供按钮的标签NSAttributedString
。 kCTSuperscriptAttributeName
属性名称设置上标级别(负值也提供下标)。请注意,您需要导入CoreText/CTStringAttributes.h
才能获得它。
#import <CoreText/CTStringAttributes.h>
// ...
NSMutableAttributedString *attributedTitle = [[NSMutableAttributedString alloc]initWithString:@"22"];
[attributedTitle addAttribute:(NSString*)kCTSuperscriptAttributeName value:@"1" range:NSMakeRange(1, 1)];
[button setAttributedTitle:attributedTitle forState:UIControlStateNormal];
答案 1 :(得分:2)
引用 Unicode Charactor 它会生成下标和上标
这是一个例子,
有,
x² - U+00Bx2 -> X\u00B2
x³ - U+00Bx3 -> X\u00B3
x⁶ - U+207x6 -> X\u2076
等......
[button setTitle:@"X\u00B2" forState:UIControlStateNormal];
[button setTitle:@"X\u00B3" forState:UIControlStateNormal];
[button setTitle:@"X\u2076" forState:UIControlStateNormal];
像那样......
答案 2 :(得分:1)
让我给你两种方法:
A)使用字符查看器在NSString文字中键入上标。
角色查看器通常位于菜单栏中的日期旁边。 在搜索框中键入所需的数字。它将在相关字符下显示上标版本。双击它即可插入。
如果不存在角色查看器,请转到设置&gt;语言&amp;文字&gt;输入来源并检查&#34;键盘&amp;角色查看器&#34;
B)使用属性字符串作为按钮标签。
这是所有格式的通用解决方案。这比较困难,但适用于几乎所有事情。
答案 3 :(得分:1)
我使用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];
结果:
答案 4 :(得分:0)
请您使用此代码代替title
:
[NSString stringWithUTF8String:"foot\u00b2"];
这对我有用:
UIBarButtonItem *btnOffer=[[UIBarButtonItem alloc] initWithTitle:[NSString stringWithUTF8String:"foot\u00b2"] style:UIBarButtonItemStylePlain target:self action:@selector(btnOffer_clicked)];
self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:34.0/255.0f green:182.0/255.0f blue:226.0/255.0f alpha:1.0];
[self.navigationItem setRightBarButtonItem:btnOffer];