user718229
user718229

Reputation: 573

How to switch back to original button image after delay (obj-c)?

Hi I am trying to make a simple app that includes buttons changing images on click. I would like them to switch back to the original after a delay of 2 - 3 seconds. Im new to objective c and cant figure out how to do it. I've tried variations of the code below. Since there are several buttons I'd need to retain the sender id or image name. Thanks in advance!

- (IBAction)playSound:(id)sender {   
    UIImage *newImage = [UIImage imageNamed:@"new.jpg"];
    [sender setImage:newImage forState:UIControlStateNormal];

    [NSThread sleepForTimeInterval:3];

    UIImage *origImage = [UIImage imageNamed:@"orig.jpg"];
    [sender setImage:origImage forState:UIControlStateNormal];
}

Upvotes: 1

Views: 237

Answers (2)

Vaibhav Saran
Vaibhav Saran

Reputation: 12908

You need not to change button image. Follow this:

Your UIButton will have to images for two states, UIControlStateNormal and UIControlStateSelected in loadView or in viewDidLoad of in xib itself.

[button setImage:[UIImage imageNamed:@"original.jpg"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"new.jpg"] forState:UIControlStateSelected];

when a user will click on button, button will turn to [UIImage imageNamed:@"new.jpg"] itself. Then inside playSound method fire a NSTimer

-(IBAction)playSound:(id)sender
{
    [self aTimer];
}

- (void)aTimer
{
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(changeImage) userInfo:self.view repeats:NO];
}

- (void)changeImage
{
    [button setSelected:NO];
}

Upvotes: 1

iPatel
iPatel

Reputation: 47099

Add two target of your Button with StateHighlighted and StateNormal, such like,,,

[myButton setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d.png", i]] forState:UIControlStateNormal];
[myButton setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d-active.png", i]] forState:UIControlStateHighlighted]
[myButton addTarget:self action:@selector(buttonMenuPressed:) forControlEvents:UIControlEventTouchUpInside];
[myButton addTarget:self action:@selector(gotoList:) forControlEvents:UIControlStateHighlighted];

Upvotes: 1

Related Questions