Stephen
Stephen

Reputation: 4811

UIPicker as Subview

I'm trying to add a UIPicker as a subview, but can't quite figure it out. I've added a second UIView control with a UIPickerview to my nib (NewWorkoutViewController.xib). My code is as follows:

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


-(NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component
{
    return [list count];
}


-(NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [list objectAtIndex:row];
}


-(void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSLog(@"Selected item: %@ index of selected item: %i", [list objectAtIndex:row], row);
}

-(void)viewDidLoad 
{
    [super viewDidLoad];
    counterInt = 0;

    list = [[NSMutableArray alloc] init];
    [list addObject:@"red"];
    [list addObject:@"blue"];
    [list addObject:@"yellow"];
    [list addObject:@"pink"];
}   

-(IBAction)routePicker
{   
    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 480, 320, 216)];
    UIPickerView *thePickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0,0,320,216)];
    [myView addSubview:thePickerView];
    [self.view.superview addSubview:myView];  
}

My subview is not popping up as expected.

Upvotes: 0

Views: 1547

Answers (2)

binshi
binshi

Reputation: 1328

Check out this example from Apple

Date Cell Picker

Upvotes: 0

Vladimir
Vladimir

Reputation: 170809

It is not clear why do you add the picker in code if you've already added it in IB... Regarding the code you posted, try to add picker to controller's view, not to the superview (and do not forget to set its delegate):

-(IBAction)routePicker
{   
    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 480, 320, 216)];
    UIPickerView *thePickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0,0,320,216)];
    thePickerView.delegate = self;
    [myView addSubview:thePickerView];
    [self.view addSubview:myView];  
}

Edit: You initialize you myView instance with a frame that is likely to be outside of the visible area (frame's origin y coordinate is 480), try to set it to 0:

// Bad
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 480, 320, 216)];
// Good?
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 216)]; 

Upvotes: 2

Related Questions