//初始化:
TimesPickerView = [[UIPickerView alloc] initWithFrame:CGRectZero];
CGRect pickerRect = CGRectMake(w, h, x, y);
TimesPickerView.frame = pickerRect;
TimesPickerView.showsSelectionIndicator = YES;
[TimesPickerView setBackgroundColor:[UIColor clearColor]];
TimesPickerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
TimesPickerView.delegate=self; //设置委托
[self.view addSubview:TimesPickerView];
Picker View需要两个接口:DataSource和Delegate。
在定义接口的地方要有如下定义:
一个类必须至少实现下列方法:
@interface SingleComponentPickerViewController : UIViewController
<UIPickerViewDelegate, UIPickerViewDataSource>
#pragma mark -
#pragma mark Picker Data Source Methods
- (NSInteger) numberOfComponentsInPickerView: (UIPickerView *) pickerView
{
return 1;
}
- (NSInteger) pickerView: (UIPickerView *)pickerView
numberOfRowsInComponent: (NSInteger) component
{
return [pickerData count];
}
#pragma mark Picker Delegate Methods
- (NSString *) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger) row
forComponent:(NSInteger) component{
return [pickerData objectAtIndex:row];
}
其中Data Source提供了数据,而Delegate则实际获取数据。
如果要接收某个Component被选择的消息,则要实现一个delegate方法:
- (void) pickerView:(UIPickerView *) pickerView
didSelectRow: (NSInteger) row
inComponent: (NSInteger) component{
if (component == kStateComponent) {
NSString *selectedState = [self.states objectAtIndex:row];
NSArray *array = [stateZips objectForKey:selectedState];
self.zips = array;
[picker selectRow:0 inComponent: kZipComponent animated:YES];
[picker reloadComponent:kZipComponent];
}
}
//触发事件
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
[pickerViewsarray objectAtIndex:row];
switch (row) {
case 0:
NSLog(@"row:%d",row);
break;
case 1:
NSLog(@"row:%d",row);
break;
}