views:

71

answers:

2

I'm trying to use a UIImage as a button which gives the impression of it being turned on then off again within about half a second. This works fine if I switch it on but if I want to switch it off again it doesn't switch on at all. I have a short loop in there to prevent it switching on and off so fast I can't see it but it doesn't switch on at all. I've tried it with and without the [flashingButton release]. Is there something I'm misunderstanding here? Can I addSubview and removeFromSuperView at the same time even with a short delay?

if (  some conditional statements in here .......) {

    UIImage *estimateButton1 = [UIImage imageNamed:@"FlashingButton.png"];
    flashingButton = [[UIImageView alloc] initWithImage:flashingButton1];
    flashingButton.frame = CGRectMake (146,8,165,30);
    [self.view addSubview:flashingButton];
    //  [flashingButton release];

    //      short loop in here to delay urning the button off   

    [self.flashingButton removeFromSuperview];
A: 

Looping within the main thread will just hang the program temporarily and prevent any drawing from taking place. Instead, use an NSTimer.

Jonathan Grynspan
+3  A: 

User interface drawing doesn't happen until later in the main run loop. Your call to addSubview adds flashingButton to self.view but doesn't draw it. Your short loop blocks the main run loop, so it still doesn't get to the drawing part. And then, you remove the button before the main run loop gets to draw it.

A solution is to let the main run loop continue after you've added the flashing button (so it will get drawn), but create a timer that will remove that button in the future. You can use performSelector:withObject:afterDelay: to do this.

[self.flashingButton performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:0.5f];

You can read about run loops in "Threading Programming Guide" and about how drawing gets done in "View Programming Guide for iOS."

James Huddleston
Thanks you very much James for both the code and the referral. The code does exactly what I wanted. Have a couple of drinks on me!
TrueScot
Glad to help. Thanks for the drinks!
James Huddleston