UIPickerView简单使用 - 点餐

本文介绍如何使用UIPickerView实现一个动态选择菜单,并通过代码展示了如何设置数据源、代理及响应选择事件,最后演示了随机选择的功能。

1.先看视图


2.拖线设置数据源和代理后,代码如下:

//
//  ViewController.m

#import "ViewController.h"

@interface ViewController ()<UIPickerViewDataSource,UIPickerViewDelegate>

@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;

@property(nonatomic,strong)NSArray *foods;

@property (weak, nonatomic) IBOutlet UILabel *frultLabel;
@property (weak, nonatomic) IBOutlet UILabel *mainLabel;
@property (weak, nonatomic) IBOutlet UILabel *drinkLabel;

@end

@implementation ViewController

/**
 *  随机
 */
- (IBAction)random
{
    // pickerView每一列随机选中一行
    for (int i=0; i<3; i++) {
        NSInteger count = [self.foods[i] count];
        int random = arc4random_uniform((u_int32_t)count);

        [_pickerView selectRow:random inComponent:i animated:YES];
        
        // 随机选中的文字展示到label
        [self pickerView:_pickerView didSelectRow:random inComponent:i];
    }
}


- (NSArray *)foods
{
    if (_foods == nil) {
        // 加载本地plist文件
       NSString *filePath = [[NSBundle mainBundle] pathForResource:@"foods" ofType:@"plist"];
        // 从文件中创建数组
       _foods =  [NSArray arrayWithContentsOfFile:filePath];
    }
    return _foods;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化label数据
    for (int i = 0; i < 3; i++) {
        [self pickerView:_pickerView didSelectRow:0 inComponent:i];
    }
    
}

#pragma mark - UIPickerViewDataSource

/**
 *  返回pickerView有多少列
 */
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return self.foods.count;
}

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

#pragma mark - UIPickerViewDelegate
/**
 *  返回第component列的第row行的标题
 */
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return self.foods[component][row];
}

/**
 *  选中了第component列的第row行的时候调用
 *  注意:这个方法必须用户主动推动pickerView
 */
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
//    NSLog(@"%ld,%ld",component,row);
    switch (component) {
        case 0:
            _frultLabel.text = self.foods[component][row];
            break;
        case 1:
            _mainLabel.text = self.foods[component][row];
            break;
        case 2:
            _drinkLabel.text = self.foods[component][row];
            break;
    }
}


@end
3.演示效果


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值