如何根据FirstPickerView选择值在SecondPickerView中显示值?

时间:2016-01-12 07:39:41

标签: ios objective-c uipickerview didselectrowatindexpath

我有2个选择器视图:statePickerproviderPicker。我为两个选择器视图填充了数组的值(stateNamesstatePickerproviderNamesproviderPicker

我的问题是,我必须根据providerPicker的所选值在statePicker中显示一个值。例如,如果我在Tamilnadu中选择statePicker表示providerPicker会自动显示TNEB。同样,KSEBKarnataka

这是我的代码:

DetailDeviceViewController.h

#import <UIKit/UIKit.h>

@interface DeviceDetailViewController : UIViewController<UIPickerViewDelegate, UIPickerViewDataSource>

@property(strong,nonatomic) UIPickerView *statePicker;
@property(strong,nonatomic) UIPickerView *providerPicker;
@property (strong, nonatomic) NSArray *stateNames;
@property (strong, nonatomic) NSArray *providerNames;

@end

DetailDeviceViewController.m

#import "DeviceDetailViewController.h"

@interface DeviceDetailViewController ()
@end

@implementation DeviceDetailViewController 
@synthesize stateNames,providerNames,statePicker,providerPicker;

- (void)viewDidLoad
{
    [super viewDidLoad];

    //Array declaration
    stateNames = [[NSArray alloc]initWithObjects:@"Tamilnadu",@"Karnataka", nil];
    providerNames =[[NSArray alloc]initWithObjects:@"TNEB",@"KSEB",nil];

    //statePicker
    statePicker = [[UIPickerView alloc]initWithFrame:CGRectMake(50, 50, 100, 200)];
    [statePicker setDelegate:self];
    [statePicker setDataSource:self];
    statePicker.showsSelectionIndicator =YES;
    [self.view addSubview:statePicker];

    //providerPicker
    providerPicker = [[UIPickerView alloc]initWithFrame:CGRectMake(50, 150, 100, 200)];
    [providerPicker setDelegate:self];
    [providerPicker setDataSource:self];
    providerPicker.showsSelectionIndicator =YES;
    [self.view addSubview:providerPicker];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if([pickerView isEqual:statePicker])
    {
        return 1;
    }
    else
    {
        return 1;
    }
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if([pickerView isEqual:statePicker])
    {
        return [stateNames count];
    }
    else
    {
        return [providerNames count];
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if ([pickerView isEqual:statePicker])
    {
        return [stateNames objectAtIndex: row];
    }
    else
    {
        return [providerNames objectAtIndex: row];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

3 个答案:

答案 0 :(得分:2)

UIPickerViewDelegate协议包含以下方法:

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component

选择行时,将调用此方法。

答案 1 :(得分:1)

您可以使用didSelectRow的{​​{1}}方法。

PickerView

答案 2 :(得分:0)

当您在选择器中选择值时,此委托方法将自动调用。

因此,在此方法中,您可以编写要执行的内容。

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
     // YOUR CODE HERE.
}