您好我正在尝试创建一个简单的应用程序,其中包括按钮在点击时更改图像。我希望他们在延迟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];
}
答案 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
中的UIControlStateSelected
和loadView
以及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];
}