A.需求
1.使用PickerView做出有3列餐点(水果、主菜、饮料)的搭配Demo
2.选择的餐点实时显示在“显示区”
3.提供“随机”按钮,随机选择菜品搭配
B.实现步骤
1.拖入一个PickerView
2.用控制器配置dataSource和delegate
// 遵守UIPickerViewDataSource,UIPickerViewDelegate
@interface ViewController () <UIPickerViewDataSource, UIPickerViewDelegate> /** 选择器 */
@property (weak, nonatomic) IBOutlet UIPickerView *pickerView; @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib. // 设置dataSource
self.pickerView.dataSource = self;
// 设置delegage
self.pickerView.delegate = self;
}
3.实现代理方法
#pragma mark - 代理方法
/** 列数 */
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return ;
} /** 对应列的行数 */
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return ;
} /** 对应列和行的显示内容 */
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return @"内容";
}
4.引入plist文件,读取数据
/** 加载数据,延迟加载 */
- (NSArray *) foodCategories {
if (nil == _foodCategories) {
_foodCategories = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"foods.plist" ofType:nil]];
} return _foodCategories;
} #pragma mark - dataSource方法
/** 列数 */
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return self.foodCategories.count;
} /** 对应列的行数 */
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
NSArray *foods = self.foodCategories[component];
return foods.count;
} #pragma mark - delegate方法
/** 对应列和行的显示内容 */
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
NSArray *foods = self.foodCategories[component];
return foods[row];
}
5.制作显示区
/** 水果 */
@property (weak, nonatomic) IBOutlet UILabel *fruitLabel;
/** 主菜 */
@property (weak, nonatomic) IBOutlet UILabel *mainLabel;
/** 饮料 */
@property (weak, nonatomic) IBOutlet UILabel *drinkLabel;
6.响应选择事件
/** 响应选择餐点事件 */
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
NSArray *foods = self.foodCategories[component];
NSString *food = foods[row]; switch (component) {
case :
self.fruitLabel.text = food;
break;
case :
self.mainLabel.text = food;
break;
case :
self.drinkLabel.text = food;
break;
default:
break;
}
7.制作“随机”功能
/** 随机选择餐点 */
- (IBAction)onRandomClicked {
// 循环所有餐点种类
for (int i=; i<self.foodCategories.count; i++) {
// 之前选择的餐点行数
NSInteger originalRow = [self.pickerView selectedRowInComponent:i]; NSInteger row = originalRow; // 此种类内含有的所有餐点
NSArray *foods = self.foodCategories[i];
// 如果随机的餐点跟上一次的相同,继续随机
while (row == originalRow) {
row = arc4random() % foods.count;
} // 通知pickerView改变选择
[self.pickerView selectRow:row inComponent:i animated:YES]; // 改变显示区
[self pickerView:self.pickerView didSelectRow:row inComponent:i];
}
}