문제

The following code takes the string @"ten to the power of two = 10[2]" and set red colour to the number 2

Q: I would like to have this (fancy) effect :

enter image description here

(mind that I am looking for a generic effect which represent a small, slight above line number - just after a string, not necessarily "to the power of...",nevertheless it should look like the above image):

-(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;


        }

    }
도움이 되었습니까?

해결책

You don't need to rely on special characters, you just need to adjust the baseline of the exponent section of the string so that it is superscripted.

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;

You can tweak this to parse and build strings using your provided markup - the approach is the important part. You'll probably want to specify a smaller font too with NSFontAttributeName.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top