如何取消选择单选按钮(UIButton)的先前状态

时间:2019-06-20 04:08:18

标签: ios objective-c uibutton radio-button

我在ScrollViewController中有一个Scrollview,并且在另一个ViewController(RadioViewController)中创建了单选按钮。 这是我在RadioViewController中创建单选按钮的代码:

- (void)setupBtn{

    self.radioBtn = [UIButton buttonWithType: UIButtonTypeCustom];
    [self.radioBtn setFrame:CGRectMake(40,38,18,18)];
    [self.radioBtn setImage: [UIImage imageNamed:@"radio-button"]forState:UIControlStateNormal];
    [self.radioBtn setImage: [UIImage imageNamed:@"radio-button-select"]forState: UIControlStateSelected];
    [self.radioBtn addTarget:self action:@selector(radioButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.radioBtn];
    } 
- (void)radioButtonTapped:(UIButton*)sender{
    NSLog(self.radioBtn.isSelected? @"Yes" : @"No");

    if (self.radioBtn.isSelected) {
        [self.radioBtn setSelected:NO];
        self.view1.backgroundColor =[UIColor clearColor];
        [self.radioBtn setImage:[UIImage imageNamed:@"radio-button"] forState:UIControlStateSelected];
    }else {
        [self.radioBtn setSelected:YES];
        self.view1.backgroundColor = [UACFCustomColors continentalLightBlueTransparent];
        [self.radioBtn setImage:[UIImage imageNamed:@"radio-button-select"] forState:UIControlStateSelected];

    }


}

我总是得到self.radioBtn.isSelected = NO;

当我选择一个单选按钮时,如果还选择了其他任何单选按钮,如何将那些单选按钮的状态设置为“否”?

2 个答案:

答案 0 :(得分:0)

如果要更改视图组的图像,则每个视图都需要唯一的键。

在您的方案中,为每个按钮指定了标签ID,如果用户选择了该按钮,请保留该标签ID并重新加载所有按钮。如果您的标签ID与任何按钮标签都匹配,则将该按钮设置为选中状态。

答案 1 :(得分:0)

将您的代码更改为以下代码。

BOOL radioButtonClicked;

-(void)setupBtn{
self.radioBtn = [UIButton buttonWithType: UIButtonTypeCustom];
[self.radioBtn setFrame:CGRectMake(40,38,18,18)];
[self.radioBtn setImage: [UIImage imageNamed:@"radio-button"]forState:UIControlStateNormal];
[self.radioBtn setImage: [UIImage imageNamed:@"radio-button-select"]forState: UIControlStateSelected];
[self.radioBtn addTarget:self action:@selector(radioButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.radioBtn];
radioButtonClicked = YES; // Add a boolean flag and set to YES
} 

-(void)radioButtonTapped:(UIButton*)sender{
NSLog(self.radioBtn.isSelected? @"Yes" : @"No");

if (radioButtonClicked) {
   radioButtonClicked = NO;
   self.view1.backgroundColor =[UIColor clearColor];
   [self.radioBtn setImage:[UIImage imageNamed:@"radio-button"] forState:UIControlStateSelected];
   }
else {
    radioButtonClicked = YES;
    self.view1.backgroundColor = [UACFCustomColors continentalLightBlueTransparent];
    [self.radioBtn setImage:[UIImage imageNamed:@"radio-button-select"] forState:UIControlStateSelected];

   }
}