UIPickerView选择器

#import "ViewController.h"
@interface ViewController ()
{
    NSArray *_procinceArray;
    NSArray *_hebeiArray;
    NSArray *_henanArray;
    NSArray *_anhuiArray;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    _procinceArray = [NSArray arrayWithObjects:@"河北",@"河南",@"安徽", nil];
    _hebeiArray =[NSArray arrayWithObjects:@"石家庄"@"保定"@"定州", nil];
    _henanArray = [NSArray arrayWithObjects:@"郑州",@"安阳",@"濮阳", nil];
    _anhuiArray = [NSArray arrayWithObjects:@"合肥", nil];
    //选择器高度的范围:1~179:162  180~215 :180    0或者216++:216;
    UIPickerView *pickerview = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 100, 320, 216)];
    pickerview.dataSource = self;
    pickerview.delegate = self;
    [self.view addSubview:pickerview];
}
//返回列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}
//返回每一列下的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0)
    {
        return _procinceArray.count;
    }
    if (component == 1)
    {
        //城市:不同省份对应的数据不一样,所需的行数也是不同的
        //要确定第一列有多少行数,首先要知道第0列选择哪一行;
        int selectedRow = [pickerView selectedRowInComponent:0];
        if (selectedRow == 0)
        {
            return _hebeiArray.count;
        }
        if (selectedRow == 1)
        {
            return _henanArray.count;
        }
        else
        {
            return _anhuiArray.count;
        }
    }
    return 0;
}
//是用于设置每一列中每一行的标题内容
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0)
    {
        return [_procinceArray objectAtIndex:row];
    }
    else
    {
        //首先判断第0列选择哪一行
        int selectedRow = [pickerView selectedRowInComponent:0];
        if (selectedRow == 0)
        {
            return [_hebeiArray objectAtIndex:row];
        }
        else if (selectedRow == 1)
        {
            return [_henanArray objectAtIndex:row];
        }
        else
        {
            return [_anhuiArray objectAtIndex:row];
        }
    }
    return 0;
}
//设置行的高度
-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 50;
}
//设置列的宽度
-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component

{
    if (component == 0)
    {
        return 200;
    }
    else
    {
        return 100;
    }
}
//当你选中某一列中的某一行的时候,会调用该方法
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    //如果你改变了第0列当前选中的行,及时去刷新Pickview ,你在刷新pickview的时候,上面的协议方法会被从新调用;
    if (component == 0)
    {
        //只要第0列行数改变,就去刷新第一例的数据
//        [pickerView reloadComponent:1];
        //全部刷新
        [pickerView reloadAllComponents];
        //刷新完毕之后,可以指定地1列当前选中的行;
        [pickerView selectRow:0 inComponent:1 animated:YES ];
    }
}
@end

你可能感兴趣的:(UIPickerView选择器)