iOS开发中使用Picker View实现一个点菜应用的UI示例

2020-01-14 19:02:56于海丽

    }
}

#pragma mark-使用懒加载,把数据信息加载进来
-(NSArray *)foods
{
    if (_foods==nil) {
        NSString *fullpath=[[NSBundle mainBundle]pathForResource:@"foods.plist" ofType:nil];
        NSArray *arrayM=[NSArray arrayWithContentsOfFile:fullpath];
        _foods=arrayM;
    }
    return _foods;
}

#pragma mark-处理随机按钮的点击事件
- (IBAction)randomFood:(id)sender {
    
    // 让pickerView主动选中某一行
    // 让pickerView选中inComponent列的Row行
    //    [self.pickerView selectRow:1 inComponent:0 animated:YES];
    
    /*
     [self.pickerView selectRow: arc4random() % 12 inComponent:0 animated:YES];
     [self.pickerView selectRow: arc4random() % 15 inComponent:1 animated:YES];
     [self.pickerView selectRow: arc4random() % 10 inComponent:2 animated:YES];
     */
    
    //    [self.foods objectAtIndex:0]; == self.foods[0];
    //    [self.foods[0] count];
    
    /*
     // 根据每一列的元素个数生成随机值
     [self.pickerView selectRow: arc4random() % [self.foods[0] count] inComponent:0 animated:YES];
     [self.pickerView selectRow: arc4random() % [self.foods[1] count] inComponent:1 animated:YES];
     [self.pickerView selectRow: arc4random() % [self.foods[2] count] inComponent:2 animated:YES];
     */
    
    //设置一个随机数
    for (int component=0; component<self.foods.count; component++) {
        //获取当前列对应的数据元素的个数
        int total=[self.foods[component] count];
        //根据每一列的总数生成随机数(当前生成的随机数)
        int randomNumber=arc4random()%total;
        
        //获取当前选中的行(上一次随机后移动到的行)
        int oldRow=[self.pickerView selectedRowInComponent:0];