<p>UIPickerView是一個(gè)選擇器控件,它比UIDatePicker更加通用,它可以生成單列的選擇器屯换,也可生成多列的選擇器,而且開發(fā)者完全可以自定義選擇項(xiàng)的外觀与学,因此用法非常靈活彤悔。UIPickerView直接繼承了UIView,沒有繼承UIControl索守,因此晕窑,它不能像UIControl那樣綁定事件處理方法,UIPickerView的事件處理由其委托對象完成卵佛。</p>
<p>UIDatePicker控件只是負(fù)責(zé)該控件的通用行為杨赤,而該控件包含多少列敞斋,各列包含多少個(gè)列表項(xiàng)則由UIPickerViewDataSource對象負(fù)責(zé)。開發(fā)者必須為UIPickerView設(shè)置UIPickerViewDataSource對象疾牲,并實(shí)現(xiàn)如下兩個(gè)方法植捎。</p>
- - numberOfComponentsInPickerView: 該UIPickerView將通過該方法來判斷應(yīng)該包含多少列。
- - pickerView:numberOfRowsInComponent: 該UIPickerView將通過該方法判斷指定列應(yīng)該包含多少個(gè)列表項(xiàng)阳柔。
<p>如果程序需要控制UIPickerView中各列的寬度焰枢,以及各列中列表項(xiàng)的大小和外觀,或程序需要為UIPickerView的選中事件提供響應(yīng)舌剂,都需要為UIPickerView設(shè)置UIPickerViewDelegate委托對象济锄,并根據(jù)需要實(shí)現(xiàn)該委托對象中的如下方法。</p>
- - pickerView:rowHeightForComponent: 該方法返回的CGFloat值將作為該UIPickerView控件中指定列中列表項(xiàng)的高度霍转。
- - pickerView:widthForComponent: 該方法返回的CGFloat值將作為該UIPickerView控件中指定列的寬度荐绝。
- - pickerView:titleForRow:forComponent: 該方法返回的NSString值將作為該UIPickerView控件中指定列的列表項(xiàng)的文本標(biāo)題。
- - pickerView:viewForRow:forComponent:reusingView: 該方法返回的UIView控件將直接作為該UIPickerView控件中指定列的指定列表項(xiàng)谴忧。
- - pickerView:didSelectRow:inComponent: 當(dāng)用戶單擊選中該UIPickerView控件的指定列的指定列表項(xiàng)時(shí)將會激發(fā)該方法很泊。
// 監(jiān)聽輪子的滾動(dòng)
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
if (component == kStateComponent) {
NSString * selectedState = self.firstArr[row];
self.secondArr = self.dataDic[selectedState];
// !!! 更新第二個(gè)輪子的數(shù)據(jù)
[_pick reloadComponent:kZipcomponent];
[_pick selectRow:0 inComponent:kZipcomponent animated:YES];
}
// 獲取UIPickerView的不同的component選中的那行
NSInteger stateRow = [self.pick selectedRowInComponent:kStateComponent];
NSInteger zipRow = [self.pick selectedRowInComponent:kZipcomponent];
NSString *state = self.firstArr[stateRow];
NSString *zip = self.secondArr[zipRow];
NSString * title = [[NSString alloc] initWithFormat:@"You selected zip code %@",zip];
NSString * message = [[NSString alloc] initWithFormat:@"%@ is in %@",zip,state];
//官方解釋:UIAlertView is deprecated in iOS 8. (Note that UIAlertViewDelegate is also deprecated.) To create and manage alerts in iOS 8 and later, instead use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert. (主要是說UIAlertView在iOS 8中被廢棄了,取而代之的是UIAlertController)
UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
[alert addAction:action];
[self presentViewController:alert animated:YES completion:nil];
}