質問

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