views:

237

answers:

2

I tried just making the image switch to black and then use sleep(1) and have it go back to the original image, but the sleep doesn't work at the right time, and I can't even see the black flash it goes so fast.

[blueButton setImage:[UIImage imageNamed:@"black.png"] forState:UIControlStateNormal]; sleep(3); [blueButton setImage:[UIImage imageNamed:@"blue.png"] forState:UIControlStateNormal];

I just want to make it give a indicator to this button. Any thoughts? Thanks.

+1  A: 

Call a timer to notify you after a given time intercal:

[+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats][1]

Give it a simple method as the selector, which changes the image back to blue.

[blueButton setImage:[UIImage imageNamed:@"black.png"] forState:UIControlStateNormal];
[NSTimer timerWithTimeInterval:yourTimeInterval target:self selector:@selector(changeButtonBack:) userInfo:nil repeats:NO];

-(void) changeButtonBack:(id)sender{
    [blueButton setImage:[UIImage imageNamed:@"blue.png"] forState:UIControlStateNormal];
}

Now this method will be called after whatever time interval you specify, and the button will go back to blue!

Note: After you make this call, your code continues executing. This is called setting up a call-back, because your code keeps on executing, and after the specified time, the system calls you back and tells you to execute the specified function.

If you want to have different behaviour in different places, you could either specify different selectors (read:methods to be called-back), or you could pass in an object of some sort as the userInfor argument, which I set as nil in the example. Then when you get called back, check the value of the userInfo object and do what you want based on what it is.

Chris Cooper
aha. thank you.
marty
No problem! Good luck.
Chris Cooper
So for the yourTimeInterval parameter, if I wanted a second in between image switches, would I just put a 1, or does it have to be of type NSTimeInterval, as it says in the API?
marty
NSTimeInterval is just a double, so you can pass a 1.0 or any value in there.
lucius
Ok say I don't want to execute a specific method, because I want to be able to use this in several cases, so I just want it to fire and do nothing, and then run the next line of code after a second or two. How would I do that?
marty
Or does it schedule the event to happen and then go on with the rest of the code, and not wait the actual second to do the blink?
marty
@marty: See my answer update.
Chris Cooper
A: 

You need to use a NSTimer so that you change the image, then schedule a timer to change the image again 3 seconds later.

The reason sleep(3) doesn't work is because the image update doesn't happen until control returns to the run loop, after you've returned from your method (function).

lucius
ah. well thats sort of silly isn't it.
marty