ios ui 基础-UIPickerview的简单实现餐厅功能
uipickerview 选择器的使用,通过简单的餐厅点餐系统设置
操作方法
- 01
#import "ViewController.h" @interface ViewController ()<UIPickerViewDelegate,UIPickerViewDataSource> @property(strong,nonatomic) IBOutlet UILabel *fruitlab; @property (strong, nonatomic) IBOutlet UIPickerView *pickview; @property(strong,nonatomic) IBOutlet UILabel *staplelab; @property(strong,nonatomic) IBOutlet UILabel *dinklab; @property(nonatomic,strong)NSArray *foods; -(IBAction)randomfood:(id)sender; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. for (int component = 0; component<self.foods.count; component++) { [self pickerView:nil didSelectRow:0 inComponent:component]; } //记得设置代理哦!! self.pickview.dataSource = self; self.pickview.delegate =self; } #pragma mark - 加载数据 -(NSArray *) foods { if (_foods==nil) { NSString *fullpath = [[NSBundle mainBundle ]pathForResource:@"foods" ofType:@"plist"]; NSArray *arrayM= [NSArray arrayWithContentsOfFile:fullpath]; _foods = arrayM; } return _foods; } //随机点餐功能 --随机 -(IBAction)randomfood:(id)sender { int count =self.foods.count; for (int i=0; i<count; i++) { [self randomcompoment:i]; } } //随机选中某一列的方法 -(void)randomcompoment:(int)component { int sel = [self.pickview selectedRowInComponent:component]; int index = sel; while (index == sel) { index = arc4random_uniform([self.foods[component] count]); } [self.pickview selectRow:index inComponent:component animated:YES]; [self pickerView:nil didSelectRow:index inComponent:component]; } #pragma mark--设置数据源的实现方法 //多少列 -(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { return _foods.count; } //多少行 -(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { NSArray *arayM= _foods[component]; return arayM.count; } //每行显示什么,第component列第row行显示什么 -(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { NSArray *arayM= _foods[component]; NSString *name = arayM[row]; return name; } #pragma mark - 设置下拉刷新 -(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { NSString *name = _foods[component][row]; if (0==component) { self.fruitlab.text = name; }else if(1==component) { self.staplelab.text = name; }else { self.dinklab.text =name; } } #pragma mark - 是否隐藏状态栏 -(BOOL)prefersStatusBarHidden { return NO; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end