0
我已經創建了2個自定義單選按鈕,但選擇工作不正常。當我按下第一個單選按鈕時,它不會被選中,但當我再次按下它時,或者如果我按第二個單選按鈕,則第一個單選按鈕會響應。自定義單選按鈕無法正常工作iPhone
這是.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語句「並跳轉到‘其他’的一部分,但是當我再次選擇第一個單選,然後完成‘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;
}
}
我仍然得到了同樣的問題之間的差異.....是代碼的其餘部分是否正確? – 2015-02-01 01:13:04