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

1.9k Views Asked by At

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!

2

There are 2 best solutions below

1
On BEST ANSWER

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];
}
0
On

Try like this :

[UIView animateWithDuration:1.0
                         animations:^{
                             button.titleLabel.alpha:0.0f;
                         }
                         completion:^(BOOL finished){
                              button.titleLabel.text = @"Changed text";
                         }
];
[UIView animateWithDuration:1.0
                         animations:^{
                             button.titleLabel.alpha:1.0f;
                         }
];