【发布时间】:2012-08-14 09:27:37
【问题描述】:
我尝试将以下代码从 if 语句更改为 switch 语句,但我收到一条错误消息,提示我需要一个整数而不是 id 对象。
这是我的开关:
-(void) nearestIndexAfterRotationEnded:(int)index {
NSLog(@"Selected item is: %@", [colorNames objectAtIndex:index]);
statusLabel.text = [NSString stringWithFormat:@"Selected item is: %@", [colorNames objectAtIndex:index]];
switch ([colorNames objectAtIndex:])) {
case 1:
[redButton setImage:[UIImage imageNamed:@"Btn1_1.png"] forState:UIControlStateNormal];
break;
case 2:
[redButton setImage:[UIImage imageNamed:@"Btn1_2.png"] forState:UIControlStateNormal];
break;
default:
break;
}
这是我的 if 条件语句:
-(void) nearestIndexAfterRotationEnded:(int)index {
NSLog(@"Selected item is: %@", [colorNames objectAtIndex:index]);
statusLabel.text = [NSString stringWithFormat:@"Selected item is: %@", [colorNames objectAtIndex:index]];
if ([colorNames objectAtIndex:0]) {
[redButton setImage:[UIImage imageNamed:@"Btn1_1.png"] forState:UIControlStateNormal];
}
if ([colorNames objectAtIndex:1]) {
[redButton setImage:[UIImage imageNamed:@"Btn1_2.png"] forState:UIControlStateNormal];
}
if ([colorNames objectAtIndex:2]) {
[redButton setImage:[UIImage imageNamed:@"Btn1_3.png"] forState:UIControlStateNormal];
}
if ([colorNames objectAtIndex:3]) {
[redButton setImage:[UIImage imageNamed:@"Btn1_4.png"] forState:UIControlStateNormal];
}
if ([colorNames objectAtIndex:4]) {
[redButton setImage:[UIImage imageNamed:@"Btn1_5.png"] forState:UIControlStateNormal];
}
if ([colorNames objectAtIndex:5]) {
[redButton setImage:[UIImage imageNamed:@"Btn1_6.png"] forState:UIControlStateNormal];
}
if ([colorNames objectAtIndex:6]) {
[redButton setImage:[UIImage imageNamed:@"Btn1_7.png"] forState:UIControlStateNormal];
}
if ([colorNames objectAtIndex:7]) {
[redButton setImage:[UIImage imageNamed:@"Btn1_8.png"] forState:UIControlStateNormal];
}
if ([colorNames objectAtIndex:8]) {
[redButton setImage:[UIImage imageNamed:@"Btn1_9.png"] forState:UIControlStateNormal];
}
}
感谢您的帮助
【问题讨论】:
-
你将什么类的对象放入 colorNames 中?
-
你到底想做什么?
-
我希望根据选择的数组中的对象来更改按钮图像。它是一个旋转轮,当用户旋转它时,按钮图像应该会改变
-
你甚至不需要 switch 语句......为什么不直接使用 [NSString stringWithFormat:@"Btn1_%d.png", index];
标签: iphone objective-c ios switch-statement