【发布时间】:2014-08-04 22:38:36
【问题描述】:
我想设置,如果我的发件人标签 0-6 的所有开关都关闭,应用程序会显示带有警告消息的警报,以打开至少一个开关。我现在有点不知道该怎么做。
if (switi.tag ==0 && switi.isOn == YES )
{ [self.navigationController popViewControllerAnimated:YES];
[self willMoveToParentViewController:nil];
}else if ((switi.tag ==1 && switi.isOn == YES)) {
[self.navigationController popViewControllerAnimated:YES];
[self willMoveToParentViewController:nil];
} else if ((switi.tag ==2 && switi.isOn == YES)) {
[self.navigationController popViewControllerAnimated:YES];
[self willMoveToParentViewController:nil];
} else if ((switi.tag ==3 && switi.isOn == YES)) {
[self.navigationController popViewControllerAnimated:YES];
[self willMoveToParentViewController:nil];
} else if ((switi.tag ==4 && switi.isOn == YES)) {
[self.navigationController popViewControllerAnimated:YES];
[self willMoveToParentViewController:nil];
} else if ((switi.tag ==5 && switi.isOn == YES)) {
[self.navigationController popViewControllerAnimated:YES];
[self willMoveToParentViewController:nil];
} else if ((switi.tag ==6 && switi.isOn == YES)) {
[self.navigationController popViewControllerAnimated:YES];
[self willMoveToParentViewController:nil];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Please put at least one switch on." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
}
编辑
- (void)viewDidLoad
{
[super viewDidLoad];
CGFloat y = 110;
int counter = 0;
for (NSString *key in self.kejsss) {
UILabel *labeli = [[UILabel alloc] initWithFrame:CGRectMake(50, y, 150, 30)];
UISwitch *switi = [[UISwitch alloc] initWithFrame:CGRectMake(210, y, 70, 30)];
labeli.tag = counter;
switi.tag = counter;
labeli.text = key;
labeli.textColor = [UIColor whiteColor];
switi.on = [[self.konfiggg objectForKey:key] boolValue];
[switi addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:labeli];
[self.view addSubview:switi];
self.viewtabulka.layer.borderColor = [UIColor whiteColor].CGColor;
self.viewtabulka.layer.borderWidth = 0.5;
CALayer *imageLayerRR3 = self.viewtabulka.layer;
[imageLayerRR3 setCornerRadius:5];
[imageLayerRR3 setBorderWidth:1];
[imageLayerRR3 setMasksToBounds:YES];
y += 40;
counter++;
}
}
}
}
- (IBAction)switchChanged:(UISwitch *)sender{
kokos= YES;
[self.konfiggg setObject:@([sender isOn]) forKey:[self.kejsss objectAtIndex:sender.tag]];
NSLog(@"Selected Switch - %ld (%@)", (long)sender.tag, self.kejsss[sender.tag]);
NSLog(@"Selected object - %d", [sender isOn]);
}
【问题讨论】:
-
对于初学者 DRY(不要重复自己):为重复代码创建一个函数。在这种情况下,有更好的算法,请参阅答案。