MrBr
MrBr

Reputation: 1916

Adjust Subviews Size To Superview Frame

I'm trying to understand the following issue.

I create a view like that:

UIView *subNavigation = [[UIView alloc] initWithFrame:CGRectMake(0.0 0.0, 0.0, 70.0)];

Afterwards I'm running through a loop to add buttons to that subNavigation view but I don't want to display the buttons right away:

for (int i = 0; i < 5; i++) {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(leftOrigin, 0.0, 145.8, MENU_BUTTON_HEIGHT);
    leftOrigin += 145.8;

    [button setBackgroundColor:[UIColor whiteColor]];
    [button setTitle:@"Button Content" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor greenColor] forState:UIControlStateHighlighted];

    [button setTag:i];

    [subNavigation addSubview:button];

}

So the subNavigation was created with a width of 0.0. I do not want to see the buttons when I add the subNavigation but I do. How can I make all subviews adjust to the frame width/height of their superview?

Thank you very much for your help!

Upvotes: 2

Views: 943

Answers (1)

Mick MacCallum
Mick MacCallum

Reputation: 130222

I wouldn't mess around with the superview's frame like that if your only intention is to keep its subviews hidden. Instead, I suggest you use [subNavigation setHidden:YES];. This will hide its subviews as well.

If however you are insistent on this approach, I suggest you do as @rokjarc said in his comment and work on the superview's bounds. You should also look into clipping the subviews of subNavigation.

[subNavigation setClipsToBounds:YES];

Upvotes: 3

Related Questions