如何在延迟(obj-c)后切换回原始按钮图像?

时间:2013-09-26 13:46:25

标签: ios objective-c uibutton

您好我正在尝试创建一个简单的应用程序,其中包括按钮在点击时更改图像。我希望他们在延迟2 - 3秒后切换回原版。我是目标c的新手,无法弄清楚如何做到这一点。我尝试过以下代码的变体。由于有几个按钮,我需要保留发件人ID或图像名称。提前谢谢!

- (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];
}

2 个答案:

答案 0 :(得分:1)

使用 StateHighlighted StateNormal 添加Button的两个目标,例如,,,

[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];

答案 1 :(得分:1)

您无需更改按钮图像。请遵循:

您的UIButton将需要UIControlStateNormal中的UIControlStateSelectedloadView以及viewDidLoad本身的xib中的两种状态的图像。

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

当用户点击按钮时,按钮将变为[UIImage imageNamed:@"new.jpg"]本身。然后在playSound方法内部触发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];
}