我只想设置按钮图像切换到我的IBAction中的不同图像:
if ([sender isSelected]) {
//1
UIImage *unselectedImage = [[UIImage alloc]initWithContentsOfFile:@"icon_checkbox_up"];
[sender setImage:unselectedImage forState:UIControlStateSelected];
[sender setSelected:NO];
}
else {
//2
UIImage *unselectedImage = [[UIImage alloc]initWithContentsOfFile:@"icon_checkbox_down"];
[sender setImage:unselectedImage forState:UIControlStateNormal];
[sender setSelected:YES];
}
当我点击按钮时,图像会相应改变(在注释2下),再次按下按钮后,图像就会消失。我不知道为什么会这样。我已经尝试了UIControlStateSelected和UIControlStateNormal。我错过了什么吗?
答案 0 :(得分:2)
如果您的文件名没有错,您可以尝试这种方式。希望它有所帮助!!
[buttn addTarget:self action:@selector(Selected) forControlEvents:UIControlEventTouchDown];
[buttn addTarget:self action:@selector(Unselected) forControlEvents:UIControlEventTouchUpInside];
[buttn addTarget:self action:@selector(Unselected) forControlEvents:UIControlEventTouchUpOutside];
-(void)Selected
{
UIImage *unselectedImage = [[UIImage alloc]initWithContentsOfFile:@"icon_checkbox_up"];
[buttn setImage:unselectedImage forState:UIControlStateSelected];
[buttn setSelected:NO];
}
-(void)Unselected
{
UIImage *unselectedImage = [[UIImage alloc]initWithContentsOfFile:@"icon_checkbox_down"];
[buttn setImage:unselectedImage forState:UIControlStateNormal];
[buttn setSelected:YES];
}
答案 1 :(得分:0)
将代码更改为:
if ([sender isSelected]) {
[sender setSelected:NO];
}
else {
[sender setSelected:YES];
}
并为每个UIControlState设置XIB文件中的图像。