Variable height UIView

Sunday, September 4th, 2011

In the latest iPhone app, it was necessary for a particular view to grow or shrink with respect to its visible subviews. Bellow is a quick snippet from a class called VariableHeightView, a subclass of UIView.

- (CGRect)frame
    CGRect frame = [super frame];
    float height = 0.0f;
    for (UIView *asubview in self.subviews) {
        if (![asubview isHidden]) {
            float subviewBottom = asubview.frame.size.height
                                    + asubview.frame.origin.y;
            if (subviewBottom > height) {
                height = subviewBottom;
    CGRect newFrame = CGRectMake(frame.origin.x, frame.origin.y,
                                 frame.size.width, height);
    return newFrame;

The code is fairly simple. For a view built using the Interface Builder, the VariableHeightView’s (a superview) frame function will iterative over all subviews, looking for the one lowest in the screen. Once found, it will expand to match that sub-view’s Y origin plus height.

The drawRect function of UIView will take care of rendering the VariableHeightView using the dimension of the frame function.

Leave a Reply