0

I found this code to animate a label with a typing effect. I'm trying to adapt it for attributed strings.

https://stackoverflow.com/a/11687530/1813525

I tried this but I assume that i'm just recreating the same code based on the string of an attributed string :

- (void)animateLabelShowText:(NSAttributedString*)newText characterDelay:(NSTimeInterval)delay
{
    [self.mainLabel setText:@""];

    for (int i=0; i<newText.length; i++)
    {
        dispatch_async(dispatch_get_main_queue(),
                       ^{
        [self.mainLabel setAttributedText:[[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@%C", [self.mainLabel.attributedText string], [[newText string] characterAtIndex:i]] attributes:nil]];
                       });



        [NSThread sleepForTimeInterval:delay];
    }
}

Any idea how I could preserve the formatting of my attributed text newText

Thanks for your help.

1
  • it doesnt keep the formating of my attributed text Commented Jan 25, 2016 at 18:02

1 Answer 1

1

Two issues (assuming you call animateLabelShowText:characterDelay: on a background thread).

  1. You call setText:@"" on the background thread. Don't do that.
  2. You are building each new attributed string incorrectly.

Try this:

- (void)animateLabelShowText:(NSAttributedString*)newText characterDelay:(NSTimeInterval)delay
{
    for (NSInteger i = 0; i <= newText.length; i++)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSAttributedString *str = [newText attributedSubstringFromRange:NSMakeRange(0, i)];
            self.mainLabel.attributedText = str;
        });

        [NSThread sleepForTimeInterval:delay];
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Glad I could help. Please don't forget to accept an answer that solves your issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.