UIButton does not update the image after setImage: is called

Here is the problem: I have a class that is a subclass of UIView (map). It creates a button on itself and calls changeStateIndicator: when the user touches it.

Then the card should turn over after pressing the button, and the button should change its color (in fact, the image). But this does not happen at all, so the switching starts before the button has changed. Here is my code:

//Adding a button to my view UIButton *changeStateButton = [UIButton buttonWithType:UIButtonTypeCustom]; [changeStateButton setImage:[UIImage imageNamed:imageToInitWith] forState:UIControlStateNormal]; [changeStateButton setImage:[UIImage imageNamed:imageToInitWith] forState:UIControlStateHighlighted]; changeStateButton.frame = CGRectMake(0, 0, 30, 30); changeStateButton.center = CGPointMake(self.bounds.size.width/2+([myWord length]*8)+17, 35); changeStateButton.tag = 77; [changeStateButton addTarget:self action:@selector(changeStateIndicator:) forControlEvents:UIControlEventTouchUpInside]; [self addSubview:changeStateButton]; //Method which is called when the button is touched - (void)changeStateIndicator:(UIButton *)sender { [sender setImage:[UIImage imageNamed:@"StateYellow"] forState:UIControlStateNormal]; [sender setImage:[UIImage imageNamed:@"StateYellow"] forState:UIControlStateHighlighted]; currentWord.done = [NSNumber numberWithInt:currentWord.done.intValue-10]; [self prepareForTest]; } //Method which flips the card - (void)prepareForTest { testSide = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"cal_small3"]]; [UIView transitionFromView:self toView:testSide duration:0.5 options:UIViewAnimationOptionTransitionFlipFromRight completion:nil]; } 

I assume that the sender does not alter its image until the -changeStateIndicator method has reached the end, but I'm not sure if this is the real problem. Help me please.

+4
source share
2 answers

try just deferring this call:

 dispatch_async(dispatch_get_main_queue(), ^{ [self prepareForTest]; }); 

If this kind of work, but its still not the way you want, use dispatch_after () or

 [self performSelector:@selector(prepareForTest) withObject:nil afterDelay:0.25f]; 

(You can use the second call with a time of "0" instead of sending, if you want, the same.)

+3
source

You need to go through the run cycle one more time so that the button redraws itself when the drawRect: method is called. The setImage: method setImage: simply sets the image that it will use when it is done. Instead, you start the animation before it happens. This is why a very short delay fixes the problem.

Another way to fix the situation, which may even be aesthetically more attractive, is to revive the change in the image of the button. When this animation is complete, launch another.

0
source

All Articles