上篇文章 UIPickerView的使用(一) 學習瞭如何創建單列選擇器,現在看一下如何創建多列選擇器 多列選擇器(以二列為例) 1、遵守協議和創建兩個數據源 2、創建pickView 3、實現代理 //UIPickerViewDataSource中定義的方法,該方法的返回值決定該控制項包含的列數 -
上篇文章 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.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 objectAtIndex:row]; } // 當用戶選中UIPickerViewDataSource中指定列和列表項時激發該方法 - (void)pickerView:(UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent:(NSInteger)component { NSArray *tmp = component == 0 ? _areas: _teams; 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 }
效果圖
下一篇 UIPickerView的使用(三) 是相關聯的多列選擇器的使用。