通过选择UIPickerView中的特定行无法获得值
我有一个选择器视图与国家的数组,我的观点是,当用户点击特定的行我会写一些代码取决于用户选择的元素,但不知何故它不工作,请看下面这个:通过选择UIPickerView中的特定行无法获得值
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
if ([countries objectAtIndex:0]){
NSLog(@"You selected USA");
}
}
但问题是,在NSLog中总是“你选择了美国”,不管我选哪一行。但是,当我把这行代码在这里:
NSLog(@"You selected this: %@", [countries objectAtIndex:row]);
它显示我在控制台我选择哪个国家。但是当用户点击特定行时,我需要做一些事情,而我不知道如何做到这一点,请帮助我。
快速回答:您应该使用
if ([[countries objectAtIndex:row] isEqualToString:@"USA"]) ...
尼斯回答:
定义枚举和使用的switch-case结构:
// put this in the header before @interface - @end block
enum {
kCountryUSA = 0, // pay attention to use the same
kCountryCanada = 1, // order as in countries array
kCountryFrance = 2,
// ...
};
// in the @implementation:
-(void)pickerView:(UIPickerView *)pickerView
didSelectRow:(NSInteger)row
inComponent:(NSInteger)component
{
switch (row) {
case kCountryUSA:
NSLog(@"You selected USA");
break;
case kCountryCanada:
NSLog(@"You selected Canada");
break;
case kCountryFrance:
NSLog(@"You selected France");
break;
//...
default:
NSLog(@"Unknown selection");
break;
}
}
如果我这样做,当用户选择美国或德国时,如何分配一些变量?我想我需要如果声明。 – 2013-02-27 08:00:15
好的,现在我明白你的问题了,我更新了答案。 – MrTJ 2013-02-27 08:13:18
非常感谢MrTj – 2013-02-27 08:21:29
'如果([国家objectAtIndex:0 ])'总是会评估为TRUE/YES,除非阵列国家第一个索引(索引0)处的对象恰好为空。改用'if(row == 0)'。 – 2013-02-27 08:32:33
谢谢赫尔曼:) – 2013-02-27 16:25:43