在UILabel中显示分数 [英] Display fraction number in UILabel

查看:134
本文介绍了在UILabel中显示分数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发应用程序,我必须在其中显示标签上的分数。

I am working on the app in which I have to show fraction number on label.

NSMutableAttributedString   * hogan = [[NSMutableAttributedString alloc] initWithString:self.toValue];
  [hogan setAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"DINPro-Bold" size:11.0]} range:NSMakeRange(9,6)];
  UILabel *fal = [[UILabel alloc] initWithFrame:CGRectMake(100,12, 150.0, 50)];
 fal.text = @"";
 fal.textColor = [UIColor whiteColor];

 fal.backgroundColor = [UIColor redColor];
  fal.font = [UIFont fontWithName:@"DINPro-Bold" size:18.0];



fal.attributedText=hogan;
[self addSubview:fal];

此代码的输出为1/5。我想这样显示⅕。

and the Output of this code is 1/5. I want to show like this ⅕.

我尝试过使用属性字符串,但它不起作用。

I have tried with attribute string but it doesn't work.

任何人都可以帮助我。

提前致谢。

推荐答案

我创建了以下两个辅助函数,它们将以下标或上标格式返回给定数字(0-9)的unicode字符串:

I have created the following two helper functions which will return the unicode string for a given number (0-9) in subscript or superscript format:

-(NSString *)superscript:(int)num {

    NSDictionary *superscripts = @{@0: @"\u2070", @1: @"\u00B9", @2: @"\u00B2", @3: @"\u00B3", @4: @"\u2074", @5: @"\u2075", @6: @"\u2076", @7: @"\u2077", @8: @"\u2078", @9: @"\u2079"};
    return superscripts[@(num)];
}

-(NSString *)subscript:(int)num {

    NSDictionary *subscripts = @{@0: @"\u2080", @1: @"\u2081", @2: @"\u2082", @3: @"\u2083", @4: @"\u2084", @5: @"\u2085", @6: @"\u2086", @7: @"\u2087", @8: @"\u2088", @9: @"\u2089"};
    return subscripts[@(num)];
}

宣布这些后,您可以轻松调用以下内容:

Once you have these declared, you can easily call something like this:

NSLog(@"%@/%@", [self superscript:5], [self subscript:6]);

这将输出以下内容:

⁵/₆

甚至来自我的普通 UILabel

编辑

这是一个适用于任何分数的函数,包括 37/100 ,例如:

Here's a function that will work with any fraction, including 37/100, for example:

-(NSString *)fraction:(int)numerator denominator:(int)denominator {

    NSMutableString *result = [NSMutableString string];

    NSString *one = [NSString stringWithFormat:@"%i", numerator];
    for (int i = 0; i < one.length; i++) {
        [result appendString:[self superscript:[[one substringWithRange:NSMakeRange(i, 1)] intValue]]];
    }
    [result appendString:@"/"];

    NSString *two = [NSString stringWithFormat:@"%i", denominator];
    for (int i = 0; i < two.length; i++) {
        [result appendString:[self subscript:[[two substringWithRange:NSMakeRange(i, 1)] intValue]]];
    }
    return result;
}

调用以下内容:

NSLog(@"%@", [self fraction:37 denominator:100]);

记录³⁷/Ο0

这篇关于在UILabel中显示分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆