che*_*ewy 4 objective-c nsstring addattribute core-text
下面的代码将字符串@"10加到2的幂= 10 [2]"并将红色设置为数字2
问:我想有这种(幻想)效果:

(请注意,我正在寻找一种通用效果,它代表一个小的,稍微高于行数 - 就在一个字符串之后,不一定是"......的力量",但它应该看起来像上图):
-(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;
}
}
Run Code Online (Sandbox Code Playgroud)
您不需要依赖特殊字符,只需要调整字符串的指数部分的基线,使其成为上标.
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;
Run Code Online (Sandbox Code Playgroud)
您可以调整它以使用提供的标记解析和构建字符串 - 该方法是重要的部分.您可能也想要指定一个较小的字体NSFontAttributeName.
| 归档时间: |
|
| 查看次数: |
1105 次 |
| 最近记录: |