UIPickerView的使用(三),uipickerview使用
前兩篇文章 UIPickerView的使用(一) 、 UIPickerView的使用(二),學習了UIPickerView的單欄選取器和雙欄選取器的使用。
現在我們一起學習相互依賴的多欄選取器
1、遵守協議
2、建立pickView
3、實現協議
//UIPickerViewDataSource中定義的方法,該方法的傳回值決定該控制項包含的列數- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView{ return 2; // 返回2表明該控制項只包含2列}//UIPickerViewDataSource中定義的方法,該方法的傳回值決定該控制項指定列包含多少個清單項目- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{ // 由於該控制項只包含一列,因此無須理會列序號參數component // 該方法返回teams.count,表明teams包含多少個元素,該控制項就包含多少行 if (component == 0) { return _areas.count; } else return [[_teams objectForKey:_selectedAreas]count]; }// UIPickerViewDelegate中定義的方法,該方法返回的NSString將作為UIPickerView// 中指定列和清單項目的標題文本- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{ // 由於該控制項只包含一列,因此無須理會列序號參數component // 該方法根據row參數返回teams中的元素,row參數代表清單項目的編號, // 因此該方法表示第幾個清單項目,就使用teams中的第幾個元素 if (component == 0) { return [_areas objectAtIndex:row]; } return [[_teams objectForKey:_selectedAreas]objectAtIndex:row]; }// 當使用者選中UIPickerViewDataSource中指定列和清單項目時激發該方法- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{ if (component == 0) { _selectedAreas = [_areas objectAtIndex:row]; [self.pickView reloadComponent:1]; } NSArray *tmp = component == 0 ? _areas: [_teams objectForKey:_selectedAreas]; NSString *tip = component == 0 ? @"地區":@"球隊"; // 使用一個UIAlertView來顯示使用者選中的清單項目 UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"你選中的%@是:%@" , tip ,[ tmp objectAtIndex:row]] delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil]; [alert show];}// UIPickerViewDelegate中定義的方法,該方法返回的NSString將作為// UIPickerView中指定列的寬度-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{ // 如果是第一列,寬度為90 if(component == 0) { return 90; } return 210; // 如果是其他列(只有第二列),寬度為210}
: