自定义单选按钮无法正常工作iPhone

时间:2015-01-31 18:59:07

标签: ios objective-c

我创建了2个自定义单选按钮,但选择不正常。当我按下第一个单选按钮时,它没有被选中,但是当我再次按下它或按下第二个单选按钮时,第一个单选按钮会响应。

这是.h文件中的代码。我选择使用NSString存储btn值,例如如果选择1st,那么“Male”将存储在NSString中。

    @property (strong, nonatomic) UIButton *radio1;
    @property (strong, nonatomic) UIButton *radio2;
    @property (strong, nonatomic) NSString * radioString1;
    @property (strong, nonatomic) NSString * radioString2;
    -(void)radioBtnSelected:(UIButton *)btn;

.m文件中的代码

@synthesize radio1;
@synthesize radio2;
@synthesize radioString1;
@synthesize radioString2;

在“viewDidLoad”中创建自定义单选按钮。使用标签来区分两个单选按钮

//radio btns
radio1 = [[UIButton alloc]initWithFrame:CGRectMake(112, 253, 20, 20)];

//setting the tag of btn, to switch between the two
radio1.tag = 0;

//setting the on and off background image
[radio1 setBackgroundImage:[UIImage imageNamed:@"RadioButton-Unselected.png"] forState:UIControlStateNormal];
[radio1 setBackgroundImage:[UIImage imageNamed:@"RadioButton-Selected.png"] forState:UIControlStateSelected];

//setting the action event, on what to do when the btn is clicked
[radio1 addTarget:self action:@selector(radioBtnSelected:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:radio1];

radio2 = [[UIButton alloc]initWithFrame:CGRectMake(225, 253, 20, 20)];
radio2.tag = 1;
[radio2 setBackgroundImage:[UIImage imageNamed:@"RadioButton-Unselected.png"] forState:UIControlStateNormal];
[radio2 setBackgroundImage:[UIImage imageNamed:@"RadioButton-Selected.png"] forState:UIControlStateSelected];
[radio2 addTarget:self action:@selector(radioBtnSelected:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:radio2];

我尝试使用断点来检查问题,我发现,当我第一次点击单选按钮时,它没有完成“if语句”并跳转到“else”部分,但是当我再次选择第一个收音机,然后完成“if语句”

-(void)radioBtnSelected:(UIButton *)btn{

switch ([btn tag]) {
    case 0:
        if ([radio1 isSelected] == YES) {
            [radio1 setSelected:NO];
            [radio2 setSelected:YES];
            radioString1 = @"Male";
            NSLog(@"%@", radioString1);
        }
       else{
            [radio1 setSelected:YES];
            [radio2 setSelected:NO];
            radioString1 = @"";
        }
        break;

     case 1:
        if ([radio2 isSelected] == YES) {
            [radio1 setSelected:YES];
            [radio2 setSelected:NO];
            radioString2 = @"Female";
            NSLog(@"%@", radioString2);
        }
        else{
            [radio1 setSelected:NO];
            [radio2 setSelected:YES];
            radioString2 = @"";
        }
        break;
    default:
        break;
}

}

1 个答案:

答案 0 :(得分:-1)

请勿将 BOOL YES

进行比较
if ([radio1 isSelected] == YES)

改为使用此表格

if ( [radio1 isSelected] )

<强> 说明

BOOL是8位变量,因此它可以保持-128到127之间的值。变量表示零值的真值和非零值的真值。有255种不同版本的真相。

是和否宏相应地具有等价1和0的整数。

详细了解 BOOL bool here

之间的差异