我希望图片在用户触摸它的第二个时间变黄。现在,在第一次点击时,图像变为灰色,释放时变为黄色。 第二次点击图片会立即回到红色。我该如何解决这个问题?
-(void)bMethod:(UIButton*)sender
{
sender.selected = !sender.selected;
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *buttonImage = [UIImage imageNamed:@"red.png"];
UIImage *buttonImageSelected = [UIImage imageNamed:@"yellow.png"];
myButton.frame = CGRectMake(200, 200, 40, 40);
[myButton addTarget:self action:@selector(bMethod:) forControlEvents:UIControlEventTouchDown];
[myButton setImage:buttonImage forState:UIControlStateNormal];
[myButton setImage:buttonImageSelected forState:UIControlStateSelected];
[myButton setImage:buttonImageSelected forState:UIControlStateHighlighted];
[self.view addSubview:myButton];
答案 0 :(得分:1)
我运行了你的代码,它的工作很好。只需仔细检查图像名称!
编辑1:
用以下代码替换您的代码:
-(void)bMethod:(UIButton*)sender
{
if (sender.imageView.image != [UIImage imageNamed:@"red.png"]){
[sender setImage:[UIImage imageNamed:@"yellow.png"] forState:UIControlStateHighlighted];
[sender setImage:[UIImage imageNamed:@"yellow.png"] forState:UIControlStateNormal];
}
else{
[sender setImage:[UIImage imageNamed:@"red.png"] forState:UIControlStateHighlighted];
[sender setImage:[UIImage imageNamed:@"red.png"] forState:UIControlStateNormal];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *buttonImage = [UIImage imageNamed:@"red.png"];
myButton.frame = CGRectMake(200, 200, 40, 40);
[myButton addTarget:self action:@selector(bMethod:) forControlEvents:UIControlEventTouchDown];
[myButton setImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:myButton];
}
编辑2:
-(void)bMethod:(UIButton*)sender
{
sender.selected = !sender.selected;
sender.highlighted = !sender.highlighted;
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *buttonImage = [UIImage imageNamed:@"red.png"];
UIImage *buttonImageSelected = [UIImage imageNamed:@"yellow.png"];
myButton.frame = CGRectMake(200, 200, 40, 40);
[myButton addTarget:self action:@selector(bMethod:) forControlEvents:UIControlEventTouchUpInside];
myButton.adjustsImageWhenHighlighted = NO;
[myButton setImage:buttonImage forState:UIControlStateNormal];
[myButton setImage:buttonImageSelected forState:UIControlStateSelected];
[myButton setImage:buttonImageSelected forState:UIControlStateHighlighted];
[self.view addSubview:myButton];
}