hit counter

Timeline

My development logbook

Make Picker 2 Data Dependent on the Selected Row of Picker 1

It is what I want to achieve: whenever a selection is changed in the top UIPicker, the choices in the second UIPicker will change accordingly.

Useful lessons from this exercise:

  • The use of API reloadAllComponents
  • The use of class extension and category
  • Identification of the UI object – apparently a == is sufficient to find out which picker instance a picker API is handling
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#import "SOViewController.h"

@interface SOViewController ()

@property (weak, nonatomic) IBOutlet UIPickerView *Picker1;
@property (weak, nonatomic) IBOutlet UIPickerView *Picker2;

@end

@interface SOViewController (SOPickerDelegate) <UIPickerViewDelegate, UIPickerViewDataSource>

@end

@implementation SOViewController
{
    NSArray* list_media;
    NSArray* list_media_channel;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    list_media = @[@"TV", @"Radio"];
    list_media_channel = @[ @[@"ABC", @"SBS"], @[@"TripleJ", @"107.1", @"CBS"]];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

@implementation SOViewController(SOPickerDelegate)

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (pickerView == _Picker1) {
        // set Picker 2 accordingly
        [_Picker2 reloadAllComponents];
    }
}

- (NSArray*) getDataByPicker:(UIPickerView *)pickerView
{
    if (pickerView == _Picker1) {
        return list_media;
    } else {
        NSArray* content = [list_media_channel objectAtIndex:[_Picker1 selectedRowInComponent:0]];
        return content;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSArray* data = [self getDataByPicker:pickerView];
    return [data objectAtIndex:row];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{

    NSArray* data = [self getDataByPicker:pickerView];
    return [data count];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

@end