2011-03-24 24 views
0

我開始開發iPhone應用程序。我需要提供一個下拉框供客戶選擇一個值,在提交時,這個值基本上會發送到數據庫。我清楚地使用UIPickerView作爲IB建立的下拉列表。在iPhone應用程序中展開和縮回下拉列表

一旦我的視圖加載,下拉列表啓用,顯示所有值。

的問題是:

  1. 一旦它被點擊我只能展開下拉列表?
  2. 一旦用戶選擇一個值,我可以收回列表嗎?

我在考慮非常以網絡爲中心的下拉式方面,但我可能會有這個錯誤。

回答

0

你有幾個選擇:

  1. 可能比較容易爲初學者:推新視圖(無論是作爲一個模態的視圖或到導航堆棧)呈現的列表是作爲他們點擊一個表格視圖他們想要的項目或作爲pickerView滾動的位置。
  2. 查看twitter應用「我的個人資料」視圖。雖然我沒有這樣做,我個人認爲這是簡單地使用didSelectRowAtIndex來確定用戶單擊的部分,然後填充值的那部分數組之前調用[的tableView reloadData]
1

您的視圖控制器需要實施UIPickerViewDataSource以及UIPickerViewDelegate。在UIPickerView的XIB中,您需要將文件的所有者與UIPickerView的委託和數據源相關聯。

像在UITabelDataSource中一樣,您需要提供[numberOfComponentsInPickerView]中的組件數量(表格:部分)。然後您需要提供[numberOfRowsInComponent]中每個組件的行數。最後,您需要爲[titleForRow]中的每個條目提供標題。

現在爲了讓所有東西都可以使用,您可以使用[didSelectRow]加載下一個組件,如果選擇了上一個組件。

注意: UIPickerView具有一個小錯誤不調用[didSelectRow]當組件被填充/改變。爲了使它更流暢地工作,我添加了一個「無」條目作爲第一個條目,它是一個非選擇條目,並且不會導致下一個組件被加載。

這是一個最起碼的準則:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { 
    return 3; // Number of Components aka Columns 
} 

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { 
    if(component == 0) { 
     return [self.firstColumnEntries count] + 1; 
    } else if(component == 1) { 
     return [self.secondColumnEntries count] + 1; 
    } else if(component == 2) { 
     return [self.thirdColumnEntries count] + 1; 
    } 
    return 0; 
} 

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { 
    NSLog(@"titleForRow(), component: %d, row: %d", component, row); 
    NSDictionary *item = nil; 
    if(row == 0) { 
     return @" --- "; 
    } else { 
     int correctedRow = row - 1; 
     if(component == 0) { 
      item = [self.firstColumnEntries objectAtIndex:correctedRow]; 
     } else if(component == 1) { 
      item = [self.secondColumnEntries objectAtIndex:correctedRow]; 
     } else if(component == 2) { 
      item = [self.thirdColumnEntries objectAtIndex:correctedRow]; 
     } 
     return [item objectForKey:@"name"]; // My objects are NSDictionarys 
    } 
} 

- (void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { 
    DLog(@"SSVC.didSelectRow(), component: %d, row: %d", component, row); 
    ActionRequest *action = nil; 
    if(row == 0) { 
     if(component == 0) { 
      [self refreshFirstColumn:self.firstColumnEntries]; 
     } else if(component == 1) { 
      ... 
     } 
    } else { 
     // Last Column is selected. Now selection is complete 
     ... 
    } 
} 

因爲UIPickerView帶走了大量的空間,你不能改變它的大小,我建議將其放置在一個額外的UIView(使其餘透明)和顯示器當用戶選擇分配給該值的字段(UITextField)時。當選擇完成時(無論是在選擇上一個值還是在用戶輸入按鈕時),都讓View消失並將值設置到UITextField上。確保無法編輯UITextField,並且輸入它使得​​帶有拾取器視圖的視圖出現。完成後請確保您也移動到下一個字段。