Search code examples
iosobjective-cuiviewuipickerview

multiple UIPickerViews - without a .xib


I have a view. I would like to be able to put 1-3 UIPickerViews in it. The number of UIPickerViews is determined by the value of a variable myVariable. Each UIPickerView is different. Some of the values for myVariable mean that there will only be one UIPickerView in the view, but some mean that I will have to put 2 or 3 in the view, and it will be laid out vertically (so one UIPickerView is directly above the other). Right now, every case where myVariable means that it needs only 1 UIPickerView, I'm putting them in the view like this:

if (myVariable == kNeedsOnlyOnePicker)
{
    myPicker = [[UIPickerView alloc] initWithFrame:self.view.frame];
    [myPicker setDelegate:self];
    [myPicker setDataSource:self];
    myPicker.showsSelectionIndicator = YES;
    [self.view addSubview:myPicker];
}

However, I'm just not sure how to tell the code something like this:

if (myVariable == kNeedsTwoPickers)
{
     // put myPicker and myOtherPicker in self.view, 
     // and put myPicker above myOtherPicker.
}

I have a hunch I won't be able to use the .xib to do something like this, because I won't be able to set up different layouts (e.g. picker 1 above picker 2, picker 2 above picker 3, only picker 3).

TL;DR how do I programmatically say, "this subview will go above this other subview" or "this picker will go above this other picker"?

Specific methods/examples and/or general ideas would be great.

Thanks!


Solution

  • I found that I could set the frame for the subview and calculate its coordinates.

    - (void)layout
    {
        for (int i= 0; i < [self.view.subviews count]; i++)
        {
            // calculate x, y, width, and height
            UIView *subview = [self.view.subviews objectAtIndex:i];
    
            subview.frame = CGRectMake(x, y, width, height);
        }
    }