利用UIPickerView实现一个简单的点菜界面,如下图所示。源码地址:https://github.com/xiaoLong1010/iOSAppDemo.git
UIPickerView有两个协议UIPickerViewDataSource,UIPickerViewDelegate,它们为UIPickeView提供数据和代理。UIPickeView的三个component分别代表fruit,main,drink,选中某一行,菜名在下面显示。最上面的随机按钮,则实现随机点菜功能。
1.viewController实现两个协议,并且引用相关数据和控件。
@interface CsyViewController () <UIPickerViewDataSource,UIPickerViewDelegate> @property (strong,nonatomic) NSArray *foodGroups; @property (weak, nonatomic) IBOutlet UIPickerView *picker; @property (weak, nonatomic) IBOutlet UILabel *fruitLabel; @property (weak, nonatomic) IBOutlet UILabel *mainLabel; @property (weak, nonatomic) IBOutlet UILabel *drinkLabel; @property (weak, nonatomic) IBOutlet UIButton *randBtn; @end
2.数据保存在plist文件中,由foodGroup引用,并且使用懒加载读取数据。
//重写getter方法,懒加载实现 - (NSArray *)foodGroups { if (!_foodGroups) { NSString *path = [[NSBundle mainBundle] pathForResource:@"foods.plist" ofType:nil]; _foodGroups = [NSArray arrayWithContentsOfFile:path]; } return _foodGroups; }
3.UIPickerViewDataSource提供的相关信息:component数以及每个component有多少行
#pragma mark -- UIPickerViewDataSource //返回component数 - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { return self.foodGroups.count; } //返回每个component有多少行 - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { return [self.foodGroups[component] count]; }
4.UIPickerViewDelegate提供每一行显示的数据。
#pragma mark -- UIPickerViewDelegate //每一行显示的数据,字符串数据 - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { return self.foodGroups[component][row]; }
5.在UIPickerView选中某一行后,需要动态更改下方的菜名。这个是通过UIPickerViewDelegate协议的didSelectRow:方法实现的,当选中某一行,会自动调用该方法。即在该方法中动态地改变菜名。
- (void)viewDidLoad { [super viewDidLoad]; // for (NSArray *group in self.foodGroups) { // CsyLog(@"%@",group); // } //初始化三个label,菜单名 for (int i = 0; i < self.foodGroups.count; i++) { [self pickerView:self.picker didSelectRow:4 inComponent:i]; } // NSInteger row = [self.picker selectedRowInComponent:0]; // CsyLog(@"selected row = %d",row); //监听方法 [self.randBtn addTarget:self action:@selector(randBtnDidClick:) forControlEvents:UIControlEventTouchUpInside]; } #pragma mark --randBtn Listener - (void)randBtnDidClick:(UIButton *)button { // CsyLog(@"click"); for (int i = 0; i < self.foodGroups.count; i++) { NSArray *group = self.foodGroups[i]; NSInteger newRow = arc4random() % group.count; //之前被选中的行 NSInteger currentRow = [self.picker selectedRowInComponent:i]; // NSLog(@"currentRow = %d",currentRow); //如果随机值和当前的值相当,随机的值加1 if (newRow == currentRow) { newRow = (newRow + 1) % group.count; } // NSLog(@"newRow = %d",newRow); //选中某行某列 [self.picker selectRow:newRow inComponent:i animated:YES]; //调用didSecled方法,更新三个label [self pickerView:self.picker didSelectRow:newRow inComponent:i]; } }