Xcode单选按钮-按下另一个按钮时更改按钮的背景图像 [英] Xcode radio buttons- Changing background image of a button when another button is pressed
问题描述
我正在尝试实现我自己的基本单选按钮,以便一次只能选择其中一个.这是我正在使用的代码->
I'm trying to implement my own basic radio buttons, such that only one of them can be selected at a time. Here's the code I'm using->
- (IBAction)btn2Pressed:(UIButton *)sender {
[btn1 setBackgroundImage:[UIImage imageNamed:@"circle-uncheck.png"] forState:UIControlStateNormal];
btn2pressed = YES;
btn1pressed = NO;
}
- (IBAction)btn1Pressed:(UIButton *)sender {
[btn2 setBackgroundImage:[UIImage imageNamed:@"circle-uncheck.png"] forState:UIControlStateNormal];
btn1pressed = YES;
btn2pressed = NO;
}
但它不起作用,即另一个按钮的图像没有改变.:(
But it's not working, i.e. the image of the other button isn't changing. :(
我不知道自己做错了什么.
I'm not able to figure out what I'm doing wrong.
推荐答案
当您按下 2 个按钮中的任何一个时,您将背景图像设置为 circle-uncheck.png
.它是如何更改为 checked
的?我猜它会永远保持unchecked
.
When you press any of the 2 buttons, you set the background image to circle-uncheck.png
. How is it ever be changed to checked
? It will stay unchecked
forever, I guess.
编辑(由于您在下面的评论):
EDIT (due to you comment below):
如果您在界面生成器中最初设置背景图像,它们将在按下按钮后立即更改为circle-uncheck.png
,并且它们是显然永远不会设置为 checked
状态.
您必须将代码修改为类似
If you set the background images initially in the Interface Builder, they will be changed to circle-uncheck.png
as soon as a button is pushed, and they are apparently never be set to the checked
state.
You had to modify your code to something like
- (IBAction)btn2Pressed:(UIButton *)sender {
[btn1 setBackgroundImage:[UIImage imageNamed:@"circle-uncheck.png"] forState:UIControlStateNormal];
[btn2 setBackgroundImage:[UIImage imageNamed:@"circle-check.png"] forState:UIControlStateNormal];
btn2pressed = YES;
btn1pressed = NO;
}
- (IBAction)btn1Pressed:(UIButton *)sender {
[btn2 setBackgroundImage:[UIImage imageNamed:@"circle-uncheck.png"] forState:UIControlStateNormal];
[btn1 setBackgroundImage:[UIImage imageNamed:@"circle-check.png"] forState:UIControlStateNormal];
btn1pressed = YES;
btn2pressed = NO;
}
这篇关于Xcode单选按钮-按下另一个按钮时更改按钮的背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!