Search code examples
iosobjective-canimationuibuttonbeginanimations

Changing text of UIButton titleLabel during alpha is 0.0f and avoid animation of text


Im fading my UIButton.titleLabel in/out a few times like this:

[UIView beginAnimations:@"fadeOutText" context:NULL];
[UIView setAnimationDuration:1.0];
    button.titleLabel.alpha = 0.0f;
[UIView commitAnimations];

button.titleLabel.text = @"Changed text";

[UIView beginAnimations:@"fadeInText" context:NULL];
[UIView setAnimationDuration:1.0];
    button.titleLabel.alpha = 1.0f;
[UIView commitAnimations];

The thing is that i want to change the text during the time when it is hidden (alpha is 0.0f). But when I fade the text back in, the text is animated aswell. Its appearing/moving in from the right of the label.

Is there a way to avoid that the text is being animated?

The fade in and the fade out are called after each other using NSTimer.

Thanks!


Solution

  • Adding a separate code section for the text change seems to remove the animation of the text.

    This how i solved it, maybe there are better solutions?

    -(void)hideText{
        [UIView beginAnimations:@"fadeOutText" context:NULL];
        [UIView setAnimationDuration:1.0];
            button.titleLabel.alpha = 0.0f;
        [UIView commitAnimations];
        [NSTimer scheduledTimerWithTimeInterval:1.0
                                         target:self
                                       selector:@selector(setText)
                                       userInfo:nil
                                        repeats:NO];
    }
    -(void)setText{
        [button setTitle:@"changedText" forState:UIControlStateNormal];
        [NSTimer scheduledTimerWithTimeInterval:0.1
                                     target:self
                                   selector:@selector(showText)
                                   userInfo:nil
                                    repeats:NO];
    }
    -(void)showText{
        [UIView beginAnimations:@"fadeInText" context:NULL];
        [UIView setAnimationDuration:1.0];
            button.titleLabel.alpha = 1.0f;
        [UIView commitAnimations];
    }