1

您好我正在尝试制作一个简单的应用程序,其中包括单击时更改图像的按钮。我希望他们在延迟 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];
}
4

2 回答 2

1

您无需更改按钮图像。按照这个:

UIButton将不得不为两种状态提供图像,UIControlStateNormal并且UIControlStateSelected在其内部loadView或内部viewDidLoadxib

[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];
}
于 2013-09-26T14:00:27.557 回答
1

使用StateHighlightedStateNormal添加 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];
于 2013-09-26T13:51:41.820 回答