Ios 目标C中的动态单选按钮
我想在我的应用程序中设计一个动态单选按钮Ios 目标C中的动态单选按钮,ios,objective-c,xcode,radio-button,Ios,Objective C,Xcode,Radio Button,我想在我的应用程序中设计一个动态单选按钮 for (int f = 0; f<arr.count; f++) { UILabel *lbl = [[UILabel alloc]init]; lbl.frame = CGRectMake(radio_x+10,radio_y+5 , radio_w, radio_h); lbl.text = arr[f]; lbl.textColor = [UIColor blackColor]; [sel
for (int f = 0; f<arr.count; f++) {
UILabel *lbl = [[UILabel alloc]init];
lbl.frame = CGRectMake(radio_x+10,radio_y+5 , radio_w, radio_h);
lbl.text = arr[f];
lbl.textColor = [UIColor blackColor];
[self.sub_View addSubview:lbl];
self.yourButton = [[UIButton alloc] initWithFrame:CGRectMake(xPosOfTxt,radio_y , 20, 20)];
[self.yourButton setImage: [UIImage imageNamed:@"RadioButton-Selected.png"]forState:UIControlStateNormal];
[self.yourButton setImage: [UIImage imageNamed:@"RadioButton-Unselected.png"]forState: UIControlStateSelected];
[self.yourButton setTag:baseRadioTag+f];
[self.sub_View addSubview:self.yourButton];
[self.yourButton addTarget:self action:@selector(radioSelected:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)radioSelected:(UIButton*)sender {
self.yourButton.selected = false;
sender.selected = !sender.selected;
self.yourButton = sender; }
for(int f=0;f)选项2应取消选择。如果我选择了选项2,则应取消选择选项1。请帮助我完成此操作。首先让事情变得更简单
创建一个数组,该数组可以保存所有按钮的引用
@interface ViewController ()
{
NSMutableArray *btnArray;
}
创建数组的对象
- (void)viewDidLoad {
[super viewDidLoad];
btnArray = [NSMutableArray new];
/// Here is your code for creating buttons
}
现在将所有创建的按钮添加到此数组
// this is last line from your code where you create your UI
[self.yourButton addTarget:self action:@selector(radioSelected:) forControlEvents:UIControlEventTouchUpInside];
// add this line to add your button to array
[btnArray addObject:self.yourButton];
}
现在,当您单击按钮时,将调用选定的方法
注-:这里可以是两个案例,根据我,但我不知道你需要哪一个,所以我解释他们两个
第一种情况:-当您选择或取消选择按钮时,最终输出可能是没有选择按钮(所有按钮都可以取消选择)
第二种情况:-至少选择一个按钮时
-(void)radioSelected:(UIButton*)sender{
// here if current button is already selected we will not allow to deselect it and return
if(sender.isSelected){
return;
}
// here working is as same as described above
[sender setSelected:!sender.isSelected];
for (UIButton* btn in btnArray) {
if(btn.tag != sender.tag){
[btn setSelected:NO];
}
}
}
您可以测试这两种情况,并根据需要使用
希望这对你有用
如果您遇到任何问题,请告诉我:)
-(void)radioSelected:(UIButton*)sender{
// here if current button is already selected we will not allow to deselect it and return
if(sender.isSelected){
return;
}
// here working is as same as described above
[sender setSelected:!sender.isSelected];
for (UIButton* btn in btnArray) {
if(btn.tag != sender.tag){
[btn setSelected:NO];
}
}
}