首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >addAttribute到nsstring,它表示“.的威力”。

addAttribute到nsstring,它表示“.的威力”。
EN

Stack Overflow用户
提问于 2013-11-12 15:13:42
回答 1查看 1.2K关注 0票数 4

下面的代码将字符串@“10”变为2=102的幂,并将红色设置为数字2

问:我希望能产生这样的效果:

(请注意,我正在寻找一种通用效果,它代表一个较小的略高于一行的数字-就在字符串之后,而不一定是“到.的力量”,不过它应该看起来像上面的图像):

代码语言:javascript
复制
-(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;


        }

    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-12 15:25:38

您不需要依赖特殊的字符,您只需要调整字符串的指数部分的基线,这样它就会超弱。

代码语言:javascript
复制
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指定一个更小的字体。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19932838

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档