如何在UIlabel中将字符%字符显示为string?

如何在UIlabel中将字符%字符显示为string? 我知道百分比不存在于Unicode作为上标,但是有什么办法,我们可以显示%作为上标,而不是使用HTML标签?

我发现这个post上使用属性string上标脚本样式文本上的Stackoverflow:

NSAttributedString上标样式

所以使用这个,我砍了这个演示:

- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UIFont *font = [UIFont fontWithName:@"Helvetica" size:20]; UILabel *textBlock1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height / 2.0)]; textBlock1.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0]; textBlock1.textAlignment = NSTextAlignmentCenter; textBlock1.font = font; textBlock1.text = @"57%"; UILabel *textBlock2 = [[UILabel alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height / 2.0, self.view.bounds.size.width, self.view.bounds.size.height / 2.0)]; textBlock2.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0]; textBlock2.textAlignment = NSTextAlignmentCenter; NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"57%" attributes:@{NSFontAttributeName: font}]; [attributedString setAttributes:@{NSFontAttributeName : [UIFont fontWithName:@"Helvetica" size:10] , NSBaselineOffsetAttributeName : @10} range:NSMakeRange(2, 1)]; textBlock2.attributedText = attributedString; [self.view addSubview:textBlock1]; [self.view addSubview:textBlock2]; } 

结果:

在这里输入图像说明

对于简单易用的Swift解决scheme ,您可能需要签出HandyUIKit 。 导入到您的项目(例如通过迦太基 – 见自述文件中的说明)后,你可以做这样的事情:

 import HandyUIKit "57^{%}".superscripted(font: UIFont.systemFont(ofSize: 20, weight: .medium)) 

这一行将返回一个NSAttributedString ,它看起来就像你正在寻找的东西 。 只需将其分配UILabelattributedText UILabel attributedText ,就是这样!


如果你正在寻找一个文本的下标 ,只需使用subscripted(font:)来代替。 它将识别CO_{2}等结构。 还有superAndSubscripted(font:)如果你想要结合两者

有关更多信息和其他示例,请参阅文档 。