//
// ViewController.m
// 044-PickerViewTest
//
// Copyright (c) 2015年 juanjuan. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()<UIPickerViewDataSource,UIPickerViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *fruitLabel;
@property (weak, nonatomic) IBOutlet UILabel *mainLabel;
@property (weak, nonatomic) IBOutlet UILabel *drinkLabel;
@property (weak, nonatomic) IBOutlet UIButton *randomButton;
- (IBAction)randomClicked;
@property (weak, nonatomic) IBOutlet UIPickerView *pickView;
@property (nonatomic, strong) NSArray *foods;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// self.fruitLabel.text = self.foods[0][0];
// self.mainLabel.text = self.foods[1][0];
// self.drinkLabel.text = self.foods[2][0];
for (int i = 0; i<self.foods.count; i++) {
[self pickerView:nil didSelectRow:0 inComponent:i ];
}
}
-(NSArray *)foods
{
if (_foods == nil) {
_foods = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"foods" ofType:@"plist"]];
// _foods = @[[ @"aaa",@"bbb"]];
}
return _foods;
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return self.foods[component][row];
//return @"哈哈";
}
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
CGFloat componentWidth = 0.0;
if (component == 0)
componentWidth = 100.0; // 第一个组键的宽度
else if(component == 1)
componentWidth = 140.0; // 第2个组键的宽度
else
componentWidth = 100;
return componentWidth;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
return 44.0;
}
//对应每个label的显示
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (component == 0) {
self.fruitLabel.text = self.foods[component][row];
}else if(component == 1){
self.mainLabel.text = self.foods[component][row];
}else if(component == 2){
self.drinkLabel.text = self.foods[component][row];
}
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return self.foods.count;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
NSArray *subfoods = self.foods[component];
return subfoods.count;
}
- (IBAction)randomClicked {
for (int component = 0; component < self.foods.count; component++) {
//第component列数组的总长度
int count = [self.foods[component] count];
int oldRow = [self.pickView selectedRowInComponent:component];
int randowRow = arc4random()%count;
while(randowRow == oldRow)
{
randowRow = arc4random()%count;
}
//让pickview主动选择第component列的第randowRow列
[self.pickView selectRow:randowRow inComponent:component animated:YES];
//设置label的文字
[self pickerView:nil didSelectRow:randowRow inComponent:component];
}
}
@end