Question

I'm running into issues with my UI when adding a dynamic number of child UIView elements into a "container" UIView. Basically I need to be able to dynamically resize the container view (self.containerAView below) to fit the height of all the "children" subViews that have been added to it. All the attempts that I have done thus far to reset the frame haven't worked. It is worth noting that the initial size is defined in the *.xib file that is initially loading the containerAView (UIView) element with an initial size of 300x200 (w x h).

- (void)drawScreen {
    // handle all screen presentation initialization here
    // programatically create a dynamic number of child views to add to the container view
    for (int i = 0; i < 3; i++) {
        int childViewHeight = 60;
         int childViewWidth = 300;

        UIView *childView = [[UIView alloc] initWithFrame:CGRectMake(0, (i * childViewHeight) + (i * 10), childViewWidth, childViewHeight)];
    childView.backgroundColor = [UIColor blackColor];

    [self.containerAView addSubview:childView];
    }

    // build a mapping dictionary for all child elements in the container view
    NSMutableDictionary *containerASubViewDictionary = [[NSMutableDictionary alloc] init];
    for (int i = 0; i < [self.containerAView.subviews count]; i++) {
        [containerASubViewDictionary setValue:self.containerAView.subviews[i] forKey:[NSString stringWithFormat:@"childView%d", i]];
    }

    // WHAT TO ADD HERE TO HANDLE RESIZING self.containerAView height???
}

Any sort of help on dynamically resizing the container view would be greatly appreciated as I have been unable to find any solution as of yet.

Was it helpful?

Solution

One way, which is probably the most up to date approach, would be to add 4 auto layout constraints to the containerview in interface builder.

Add the four constraints: x = 0, y = 0, width = 300 & height = 200

Now click on the width constraint in interface builder to highlight it and then control drag it into your .h file and give it a name, like containerWidth.

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *containerWidth;

Repeat with the height.

In your .m file you can adjust the height and width in your drawScreen method by manipulating the contstraints.

self.containerWidth.constant = width; // your calculated new width
self.containerHeight.constant = height; // your calculated new height

OTHER TIPS

You seem to be attempting to change the height of your container's frame. A frame has an origin and a size. Try manipulating these properties:

self.containerView.frame.origin.x
self.containerView.frame.origin.y
self.containerView.frame.size.height
self.containerView.frame.size.width
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top