iOS基础-UIKit框架-高级视图-UIPickerView-实例1:点菜(列与列之间无关系)

一、点菜
0.准备一个plist文件,Root为Array,其中包含3个数组,每个数组有一堆食物名称
加载这个plist文件

@property(nonatomic,strong)NSArray *foods;
-(NSArray *)foods
{
  if(_foods == nil){
  NSString *fullPath = [[NSBundle mainBundle] pathForResource:@"foods.plist" ofType:nil];
  _foods = [NSArray arrayWithContentsOfFile:fullPath];
  }
  return _foods;
}

 

1.拖一个Picker View控件,设置数据源,遵从数据源协议并实现数据源方法

#pragma mark - 数据源方法
//返回pickerView一共有多少列
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
   return self.foods.count;
}

//返回pickerView第component列有多少行
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponents:(NSInteger)component
{
   return self.foods[components].count;
}

 

2.设置代理,遵从代理协议并实现代理方法

#pragma mark - 代理方法
//返回第component列的第row行显示什么内容
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponents:(NSInteger)component
{
   return self.foods[components][row];
}

 

二、显示点菜结果
1.拖一个UIView,并在这个UIView上拖6个标签,并将随滚动变化的标签连线
2.实现代理方法(监听选中行)

#pragma mark - 代理方法
//当选中了pickerView的某一行的时候调用
//会将选中的列号和行号作为参数传入
//只有通过手指选中某一行的时候才会调用
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
   //1.获取对应列对应行的数据
  NSString *name = self.foods[component][row];
  //2.判断选择的是哪一列,根据列号设置对应的数据
  if0 == component){
  //水果
  self.fruitLabel.text = name;
  } else if1 == component) {
   //主菜
   self.stapleLabel.text = name;
   }   else{
    //饮料
   self.drinkLabel.text = name;
   }
}

 


3.在ViewDidLoad中设置显示的默认值(模拟手动选中)

forint component = 0; component<self.foods.count;component++){

    [self pcikerView:nil didSelectRow:0 inComponent:component];
}

 

 

三、随机选菜
1.拖一个UIView(高度为64,包括状态栏的20),在上面拖1个按钮和1个标签
//居中小技巧:Y为64,(和高度一样),高度为44.
2.监听按钮点击(连线并实现方法)

//这里要拿到pickerView,调用它的方法,所以先将pickerView连线(Outlet)。
#pragma mark - 监听按钮点击
-(IBAction)randomFood:(UIButton *)sender

{
  //让pickerView主动选中某一行
  //让pickerView选中inComponent列的Row行
  //根据每一列的元素个数生成随机值
  forint component = 0;component <self.foods.count;component++)
  {
  //获取对应列的数据总数
  int total = [self.foods[component] count];
  // 根据每一列的总数生成随机数(当前生成的随机数)
  int randomNumber = arc4random() % total;

  //获取当前选中的行(上一次随机后移动到的行)
  int oldRow = [self.pickerView selectedRowInComponent:0];
  //比较上次的行号和当前生成的随机数是否相同,如果相同,重新生成
  while(oldRow == randomNumber){
  randomNumber = arc4random() % total;
   }

  //让pickerVier滚动到某一行
  [self.pickerView selectRow:randomNumber inComponent:component animated:YES];

  //通过代码选中某一行
  [self pcikerView:nil didSelectRow:randomNumber inComponent:component];
}
//% 12则永远是[0,11],其他同理,也就是说,有几个数就%几

 

问:为什么不用self.foods[0].count而用[self.foods[2] count] ?
答:因为self.foods[0] == [self.foods objectAtIndex:0];
而objectAtIndex:方法的返回值是id,id是动态类型,只有运行的时候才知道是什么类型,动态类型没有count方法,所以不能这样调用。而是采取老土的方法[self.foods[2] count]

posted on 2015-08-11 14:34  Marshall_Yin  阅读(226)  评论(0编辑  收藏  举报