<p>UIPickerView是一個選擇器控件,它比UIDatePicker更加通用,它可以生成單列的選擇器,也可生成多列的選擇器,而且開發者完全可以自定義選擇項的外觀,因此用法非常靈活。UIPickerView直接繼承了UIView,沒有繼承UIControl,因此,它不能像UIControl那樣綁定事件處理方法,UIPickerView的事件處理由其委托對象完成。</p>
<p>UIDatePicker控件只是負責該控件的通用行為,而該控件包含多少列,各列包含多少個列表項則由UIPickerViewDataSource對象負責。開發者必須為UIPickerView設置UIPickerViewDataSource對象,并實現如下兩個方法。</p>
- - numberOfComponentsInPickerView: 該UIPickerView將通過該方法來判斷應該包含多少列。
- - pickerView:numberOfRowsInComponent: 該UIPickerView將通過該方法判斷指定列應該包含多少個列表項。
<p>如果程序需要控制UIPickerView中各列的寬度,以及各列中列表項的大小和外觀,或程序需要為UIPickerView的選中事件提供響應,都需要為UIPickerView設置UIPickerViewDelegate委托對象,并根據需要實現該委托對象中的如下方法。</p>
- - pickerView:rowHeightForComponent: 該方法返回的CGFloat值將作為該UIPickerView控件中指定列中列表項的高度。
- - pickerView:widthForComponent: 該方法返回的CGFloat值將作為該UIPickerView控件中指定列的寬度。
- - pickerView:titleForRow:forComponent: 該方法返回的NSString值將作為該UIPickerView控件中指定列的列表項的文本標題。
- - pickerView:viewForRow:forComponent:reusingView: 該方法返回的UIView控件將直接作為該UIPickerView控件中指定列的指定列表項。
- - pickerView:didSelectRow:inComponent: 當用戶單擊選中該UIPickerView控件的指定列的指定列表項時將會激發該方法。
// 監聽輪子的滾動
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
if (component == kStateComponent) {
NSString * selectedState = self.firstArr[row];
self.secondArr = self.dataDic[selectedState];
// !!! 更新第二個輪子的數據
[_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];
}