2011-03-21 26 views
5

這裏我增加了pickerview programaticly如何給這個選擇器查看數據源

- (void)viewDidLoad { 
     [super viewDidLoad]; 
     CGRect pickerFrame = CGRectMake(0,280,321,200); 

     UIPickerView *myPickerView = [[UIPickerView alloc] init]; //Not sure if this is the proper allocation/initialization procedure 

     //Set up the picker view as you need it 

     //Set up the display frame 
     myPickerView.frame = pickerFrame; //I recommend using IB just to get the proper width/height dimensions 

     //Add the picker to the view 
     [self.view addSubview:myPickerView]; 
    } 

但現在我需要真正有它顯示的內容,不知怎麼找到時,它改變了什麼價值已更改爲。我該怎麼做呢?

+0

看看在UIPickerView數據源和委託的xcode文檔。 – MCannon 2011-03-21 20:03:54

回答

18
在.h文件中的地方

這個代碼

@interface RootVC : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource> 

指定數據源,並委託給拾取

// this view controller is the data source and delegate 
myPickerView.delegate = self; 
myPickerView.dataSource = self; 

使用下面的委託和datasouce方法

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component 
{ 

} 

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component 
{ 
    return 200; 
} 

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component 
{ 
    return 50; 
} 

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component 
{ 
    NSString *returnStr = @""; 
    if (pickerView == myPickerView) 
    {  
     returnStr = [[levelPickerViewArray objectAtIndex:row] objectForKey:@"nodeContent"]; 
    } 

    return returnStr; 
} 

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component 
{ 
    if (pickerView == myPickerView) 
    { 
     return [levelPickerViewArray count]; 
    } 
} 

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView 
{ 
    return 1; 
} 
0

您需要創建一個類來實現UIPickerViewDataSource協議,並將其實例分配給myPickerView.dataSource

+0

如何分配實例? – Michael 2011-03-21 20:14:45

+0

@Michael你只需設置myPickerView.dataSource =(你的數據源的實例)。數據源實例來自哪裏是特定於您的應用程序的。請記住,UIPickerView不保留其數據源,因此您需要在視圖控制器中創建/保留它(如果不在其他地方)。 – Tony 2011-03-22 12:08:36

相關問題