很明显,对于每个初学者来说,第一次理解这些东西有些乏味。
对了,你知道UITableViews怎么用吗?你知道UITableViewDelegate和UITableViewDataSource怎么用吗?如果你的答案是肯定的,那么想象一下UIPickerViews 就像UITableViews(但记住它们不是UITableViewControllers)。
假设,我有一个UIPickerView:
UIPickerView *objPickerView = [UIPickerView new]; // You need to set frame or other properties and add to your view...you can either use XIB code...
1) 首先,您需要通过 IB 或代码将 delegate 和 dataSource 分配给 UIPickerView。这取决于您的实现(所以这一步看起来与UITableView 非常相似,不是吗?)
像这样:
objPickerView.delegate = self; // Also, can be done from IB, if you're using
objPickerView.dataSource = self;// Also, can be done from IB, if you're using
2) 接下来,您需要定义部分的数量,如下所示:
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
return 1; // Or return whatever as you intend
}
2) 然后你需要定义你需要的行数:
- (NSInteger)pickerView:(UIPickerView *)thePickerView
numberOfRowsInComponent:(NSInteger)component {
return 3;//Or, return as suitable for you...normally we use array for dynamic
}
3)然后,为行定义标题(如果您有多个部分,则为每个部分定义标题):
- (NSString *)pickerView:(UIPickerView *)thePickerView
titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [NSString stringWithFormat:@"Choice-%d",row];//Or, your suitable title; like Choice-a, etc.
}
4) 接下来,您需要在有人点击某个元素时获取该事件(当您要导航到其他控制器/屏幕时):
- (void)pickerView:(UIPickerView *)thePickerView
didSelectRow:(NSInteger)row
inComponent:(NSInteger)component {
//Here, like the table view you can get the each section of each row if you've multiple sections
NSLog(@"Selected Color: %@. Index of selected color: %i",
[arrayColors objectAtIndex:row], row);
//Now, if you want to navigate then;
// Say, OtherViewController is the controller, where you want to navigate:
OtherViewController *objOtherViewController = [OtherViewController new];
[self.navigationController pushViewController:objOtherViewController animated:YES];
}
这就是您需要的所有实现。