2013-02-27 48 views
0

我有一個選擇器視圖與國家的數組,我的觀點是,當用戶點擊特定的行我會寫一些代碼取決於用戶選擇的元素,但不知何故它不工作,請看下面這個:通過選擇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]); 

它顯示我在控制檯我選擇哪個國家。但是當用戶點擊特定行時,我需要做一些事情,而我不知道如何做到這一點,請幫助我。

+0

'如果([國家objectAtIndex:0 ])'總是會評估爲TRUE/YES,除非陣列國家第一個索引(索引0)處的對象恰好爲空。改用'if(row == 0)'。 – 2013-02-27 08:32:33

+0

謝謝赫爾曼:) – 2013-02-27 16:25:43

回答

0

快速回答:您應該使用

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; 
    } 
} 
+0

如果我這樣做,當用戶選擇美國或德國時,如何分配一些變量?我想我需要如果聲明。 – 2013-02-27 08:00:15

+0

好的,現在我明白你的問題了,我更新了答案。 – MrTJ 2013-02-27 08:13:18

+0

非常感謝MrTj – 2013-02-27 08:21:29

相關問題