1
votes

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.

3

3 Answers

2
votes

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.

3
votes

I think that using NSTimer for this case is overkill.

UIButton exposes a convenient property named imageView that give you access to the underlying layer.

Assuming that your button is called recButton you can prepare the animation as follow:

recButton.imageView.animationImages = [NSArray arrayWithObjects:[UIImage imageNamed:@"recButtonOFF"], [UIImage imageNamed:@"recButtonON"], nil];
recButton.imageView.animationRepeatCount = 0;
recButton.imageView.animationDuration = 1.0;

and then start/stop animation in your designed selector with the following:

        [recButton.imageView startAnimating]; //start the animation

        ...

        [recButton.imageView stopAnimating]; //stop the animation
0
votes

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).