简体   繁体   English

添加一个UIButton

[英]Adding a UIButton

I need a UIButton to act as a Radio button (selection button). 我需要一个UIButton充当单选按钮(选择按钮)。 When the user clicks on the button, the color should change (to indicate that the user clicked this button), and when the user clicks the same button again (the already selected button) the color of the button should change to the default color indicating that the button was un-selected. 当用户单击按钮时,颜色应更改(以指示用户单击了此按钮),并且当用户再次单击同一按钮(已选择的按钮)时,按钮的颜色应更改为默认颜色,以指示该按钮未被选中。

How can i do this programatically ? 我如何以编程方式执行此操作?

There might be other alternatives to do this, but i require to use the button to do this. 可能还有其他选择可以做到这一点,但是我需要使用按钮来做到这一点。

You can specify different images for selected and normal button states: 您可以为所选按钮状态和普通按钮状态指定不同的图像:

[btnName setImage:selectedImage forState:UIControlStateSelected];
[btnName setImage:normalimage forState:UIControlStateNormal];

And then in button's action method simply toggle button's state between normal and selected: 然后在按钮的操作方法中,只需在正常和选定状态之间切换按钮的状态即可:

- (void) buttonAction:(UIButton*)sender{
    sender.selected = !sender.selected;
}

Put the below code in your button action. 将以下代码放入您的按钮操作中。

if([btnName isSelected]) {
     [btnName setImage:@"SelectedImage" forState:UIControlStateNormal];
     [btnName setSelected:NO];
} else {
     [btnName setImage:@"deSelectedImage" forState:UIControlStateNormal];
     [btnName setSelected:YES];
}

Hope it will be useful. 希望它会有用。

Follow below link: 请点击以下链接:

Radio Button in iPhone iPhone中的单选按钮

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM