1,数据源方法只实现了指定显示多少列( numberOfComponentsInPickerView),和每列多少行(numberOfRowsInComponent)
2,每列的每行显示什么是通过代理方法(titleForRow)
3,要得到各列各行被选中的值,其实通过得到其索引后,在数据源中去获取对应列行的数据,这时使用代理的方法didSelectRow,其参数就是当前被选中的列和行
4,获得选中的列的第几行:selectedRowInComponent
5, 设置UIPickerView去选中第几列和第几行:selectRow
#import "TXViewController.h"
@interface TXViewController () <UIPickerViewDataSource, UIPickerViewDelegate>
@property (nonatomic, strong) NSArray *foods;
@property (weak, nonatomic) IBOutlet UIPickerView *myPickerView;
@property (weak, nonatomic) IBOutlet UILabel *shuiguo;
@property (weak, nonatomic) IBOutlet UILabel *zhucai;
@property (weak, nonatomic) IBOutlet UILabel *yinliao;
- (IBAction)randomBtn;
@end
@implementation TXViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
for(int x = 0; x < self.foods.count; x++)
{
[self pickerView:nil didSelectRow:0 inComponent:x];
}
}
- (NSArray *)foods
{
if(_foods == nil)
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"foods.plist" ofType:nil];
_foods = [NSArray arrayWithContentsOfFile:path];
}
return _foods;
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return self.foods.count;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [self.foods[component] count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return self.foods[component][row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
switch (component) {
case 0:
self.shuiguo.text = self.foods[component][row];
break;
case 1:
self.zhucai.text = self.foods[component][row];
break;
case 2:
self.yinliao.text = self.foods[component][row];
break;
}
}
- (IBAction)randomBtn {
for (int x = 0; x < self.foods.count; x++) {
int oldRow = [self.myPickerView selectedRowInComponent:x];
int newRow = oldRow;
while (oldRow == newRow) {
newRow = arc4random() % [self.foods[x] count];
}
[self.myPickerView selectRow:newRow inComponent:x animated:YES];
[self pickerView:nil didSelectRow:newRow inComponent:x];
}
}
@end