简体   繁体   中英

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!

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM