如何在UIlabel中将上标%字符显示为字符串?

Sai*_*n K 9 unicode uilabel ios

如何在UIlabel中将上标%字符显示为字符串?我知道%unicode中不存在%作为上标,但有没有办法可以将%显示为上标而不是使用html标签?

Zha*_*ang 21

我在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];
}
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述

  • 我还想指出NSBaselineOffsetAttributeName并不适用于所有场景,因为你必须设置一个幻数,如果你设置了最小/最大字体大小,这将无法正确缩放. (2认同)