目标C中的动态单选按钮

问题描述 投票:0回答:1

我想在我的应用程序中设计一个动态单选按钮

 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;    }

我喜欢这个,这就像选择所有选项一样,我想一次只选择一个选项,如果我选择了选项1 - >选项2应该是未选中的。如果我选择了选项2 - >选项1应该被取消选择。请帮我这样做。

ios objective-c xcode radio-button
1个回答
1
投票

首先是为了让事情变得更轻松

创建一个可以保存所有按钮引用的数组

@interface ViewController ()
{
NSMutableArray *btnArray;
}

创建一个Array对象

- (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];
 }

现在,当您单击按钮时,将调用radioSelected方法

注意 - :根据我的说法,这可能是两种情况,但我不知道你需要哪一种,所以我要解释它们

情况首先: - 当你选择或取消选择按钮时,最终输出可以是没有选择按钮(所有都可以取消选择)

 -(void)radioSelected:(UIButton*)sender{
// here if button is selected, deselect it otherwise select it
[sender setSelected:!sender.isSelected];
for (UIButton* btn in btnArray) {
    // here we mark all other button as deselected except the current button

 if(btn.tag != sender.tag){
        // here when you deselect all button you can add a if statement to check that we have to deselect button only if it is selected
        if(btn.isSelected){
            [btn setSelected:NO];
        }
    }
}
}

CASE SECOND: - 至少选择一个按钮

 -(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];
    }
}
}

您可以根据您的要求测试这两种情况并使用。

希望这对你有用。

如果您遇到任何问题,请告诉我:)

© www.soinside.com 2019 - 2024. All rights reserved.