objective-c - 将属性添加到代表 "to the power of.."的 nsstring

标签 objective-c nsstring core-text addattribute

下面的代码取字符串@"十的二的幂 = 10[2]" 并将红色设置为数字 2

问:我想要这种(花哨的)效果:

enter image description here

(请注意,我正在寻找一种通用效果,它代表一个小的、略高于行号的行号——就在一个字符串之后,不一定是“……的力量”,尽管如此,它应该看起来像上图):

-(void)textAttribute
{
        NSString *myString = @"ten to the power of two = 10[2]";
        NSRange start = [myString rangeOfString:@"["];
        NSRange end = [myString rangeOfString:@"]"];
        if (start.location != NSNotFound && end.location != NSNotFound && end.location > start.location) {
            //NSString *betweenBraces = [myString substringWithRange:NSMakeRange(start.location+1, end.location-(start.location+1))];
            NSRange myRange = NSMakeRange(start.location+1, end.location-(start.location+1));
            NSMutableAttributedString *s =
            [[NSMutableAttributedString alloc] initWithString:myString];

            UIColor *powerColor = [UIColor redColor];
            [s addAttribute:NSForegroundColorAttributeName value:powerColor range:myRange];

            triggerLabel.text = [NSString stringWithFormat:@"Trigger words:%@",powerColor];
            triggerLabel.attributedText = s;


        }

    }

最佳答案

不需要依赖特殊字符,只需要调整字符串的指数部分的基线,使其上标即可。

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"ten to the power of 2 = 10"];
NSDictionary *exponentAttributes = @{
    NSForegroundColorAttributeName : [UIColor redColor],
    NSBaselineOffsetAttributeName : @(8)
    };
NSAttributedString *exponentAttributedString = [[NSAttributedString alloc] initWithString:@"2" attributes:exponentAttributes];
[attributedString appendAttributedString:exponentAttributedString];
triggerLabel.attributedText = attributedString;

您可以调整它以使用您提供的标记解析和构建字符串 - 方法是重要的部分。您可能还想使用 NSFontAttributeName 指定较小的字体。

关于objective-c - 将属性添加到代表 "to the power of.."的 nsstring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19932838/

相关文章:

ios - 内容未显示在 UITableViewCell 上

ios - 在 sizeToFit 之后将字形与 UITextView 的顶部对齐

ios - 类中的 extern NSString *const。

objective-c - 检查 UITextField 的输入是否仅为数字

ios - 如何在iOS中的后台线程上绘制文本?

iphone - 如何在 iPad 应用程序中允许文本突出显示?

objective-c - 在objective-c/cocoa-touch中是否有一个方便的功能来找到一个最小的数字?

ios - objective-c/c++中的反向位操作

iphone - NSSortDescriptor,获取按日期排序的最新 5 条记录

iOS:如何在 Constants.h 中转换字符串中的类型?