UIPickerView


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor cyanColor];
    self.pickerView.dataSource = self;
    self.pickerView.delegate = self;
    self.array = @[@"动物",@"鸟",@"昆虫"];
    NSArray *array1 = @[@"狮子",@"老虎",@"狼",@"狐狸"];
    NSArray *array2 = @[@"麻雀",@"老鹰",@"杜鹃"];
    NSArray *array3 = @[@"蟑螂",@"蝴蝶",@"蜜蜂"];
    
    
    _dataArray = @[array1,array2,array3];
    _subArray = _dataArray[0];
    
//    self.textField = [[UITextField alloc]initWithFrame:CGRectMake(50, 100, 314, 50)];
//    
//    _textField.backgroundColor = [UIColor whiteColor];
//    _textField.inputView = _pickerView;
//    
//    [self.view addSubview:_textField];
    _textField.inputView = _pickerView;
    

    
}

- (IBAction)btnClick:(UIButton *)sender {
    NSString *str1 =[_array objectAtIndex:[_pickerView selectedRowInComponent:0]] ;
    NSLog(@"%@",str1);
    NSString *str2 =[_subArray objectAtIndex:[_pickerView selectedRowInComponent:1]] ;
    NSLog(@"%@",str1);
    
    _showLabel.text = [NSString stringWithFormat:@"%@ 里面的 %@",str1,str2];
    
    
}



-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{

    return 2;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component == 0) {
        return _dataArray.count;
    }
    return _subArray.count;
}



- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    if (component == 0) {
        return 80;
    }else{
    
        return 100;
    }
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return 50;

}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (component == 0) {
        return _array[row];
    }
    return _subArray[row];

}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (component == 0) {
        _subArray = [_dataArray objectAtIndex:row];
        [_pickerView reloadAllComponents];
        
        
    }



}

你可能感兴趣的:(UIPickerView)