UIPickerView使用

1,数据源方法只实现了指定显示多少列( numberOfComponentsInPickerView),和每列多少行(numberOfRowsInComponent)


2,每列的每行显示什么是通过代理方法(titleForRow)


3,要得到各列各行被选中的值,其实通过得到其索引后,在数据源中去获取对应列行的数据,这时使用代理的方法didSelectRow,其参数就是当前被选中的列和行


4,获得选中的列的第几行:selectedRowInComponent


5, 设置UIPickerView去选中第几列和第几行:selectRow




#import "TXViewController.h"


@interface TXViewController () <UIPickerViewDataSource, UIPickerViewDelegate>
@property (nonatomic, strong) NSArray *foods;
@property (weak, nonatomic) IBOutlet UIPickerView *myPickerView;
@property (weak, nonatomic) IBOutlet UILabel *shuiguo;
@property (weak, nonatomic) IBOutlet UILabel *zhucai;
@property (weak, nonatomic) IBOutlet UILabel *yinliao;
- (IBAction)randomBtn;
@end


@implementation TXViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    
    for(int x = 0; x < self.foods.count; x++)
    {
        [self pickerView:nil didSelectRow:0 inComponent:x];
    }
}


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


- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return self.foods.count;
}


- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [self.foods[component] count];
}


- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return self.foods[component][row];
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    switch (component) {
        case 0:
            self.shuiguo.text = self.foods[component][row];
            break;
        case 1:
            self.zhucai.text = self.foods[component][row];
            break;
        case 2:
            self.yinliao.text = self.foods[component][row];
            break;
    }
}


- (IBAction)randomBtn {
    for (int x = 0; x < self.foods.count; x++) {
        int oldRow = [self.myPickerView selectedRowInComponent:x];
        int newRow = oldRow;
        
        while (oldRow == newRow) {
            newRow = arc4random() % [self.foods[x] count];
        }
        
        [self.myPickerView selectRow:newRow inComponent:x animated:YES];
        
        [self pickerView:nil didSelectRow:newRow inComponent:x];
    }
}
@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值