AutoLayout Dynamic .xib View Height

13,673

Solution 1

After much experimentation and reading, I have found the answer. When loading the .xib in some sort of constructor (in my case a class level convenience method), you must make sure to call [view setTranslatesAutoresizingMaskIntoConstraints:NO]; For example, I've done the following:

+ (InputView *)inputViewWithHeader:(NSString *)header subHeader:(NSString *)subHeader inputValidation:(ValidationBlock)validation
{
    InputView *inputView = [[[NSBundle mainBundle] loadNibNamed:@"InputView" owner:self options:nil] lastObject];
    if ([inputView isKindOfClass:[InputView class]]) {
        [inputView setTranslatesAutoresizingMaskIntoConstraints:NO];
        [inputView configureWithHeader:header subHeader:subHeader inputValidation:validation];
        [inputView layoutIfNeeded];
        [inputView invalidateIntrinsicContentSize];
        return inputView;
    }
    return nil;
}

Then, it's necessary to override layoutSubviews and intrinsicContentSize. Overriding layoutSubviews allows me to set the preferredMaxLayoutWidth of my label, while overriding intrinsicContentSize allows me to calculate the size based on constraints and subviews! Here is my implementation of those:

- (void)layoutSubviews {
    [super layoutSubviews];
    self.subHeaderLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.bounds);
    [super layoutSubviews];
}

- (CGSize)intrinsicContentSize {
    CGFloat height = self.headerView.bounds.size.height;
    height += self.headerInputSpacer.constant;
    height += self.inputField.bounds.size.height;
    height += self.inputButtonSpacer.constant;
    height += self.buttonView.bounds.size.height;
    CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width - 20, height);
    return size;
}

I'm sure there are ways to improve this, or better ways to make it happen, but for now it is at least sized correctly! Very useful for views that should not have user-defined frames.

Solution 2

This is my approach (Swift version):

Embed everything inside a view. Your xib hierarchy should be:

  • Your xib
    • View
      • Everything else, your labels, buttons etc.

View's constraint should constraint to Top, Leading and Trailing to superview(your xib), and inside your "everything else", there should be an object's bottom constraint to the superview (View).

In your code:

Load the nib

nib.frame.size.width = 80 // Set your desired width here

nib.label.text = "hello world" // Set your dynamic text here

nib.layoutIfNeeded() // This will calculate and set the heights accordingly

nib.frame.size.height = nib.view.frame.height + 16 // 16 is the total of top gap and bottom gap of auto layout

For my case, I'm loading this xib into collection view's cell, the xib's height is to be dynamically adjusted, and the width is to follow cell's width. Lastly, the above code block is inside my cellForItemAt method of the collection view.

Hope it helps.

Share:
13,673

Related videos on Youtube

anon_dev1234
Author by

anon_dev1234

Updated on September 15, 2022

Comments

  • anon_dev1234
    anon_dev1234 over 1 year

    I've not been able to find much in the way of AutoLayout with individual .xib files...

    I've got a standalone .xib file that has 3 views - a header view (which contains two labels), an input, and a footer (which contains two buttons). It looks like this:

    enter image description here

    The labels in the header view have constraints which should affect the vertical size of the header view, and in turn the size of the entire view. The subheader is a label with 0 lines, which means it is multi-line and dynamic. Everything else has a set height with horizontal constraints to superview and top constraints to sibling (or superview in header view's case).

    The issue I am having is that when I load this .xib file in code for display, the height is always static based on what is defined in Xcode's inspectors. Is it possible to make the height of the entire view dynamic based on the width (which affects dynamic label height and therefore rest of the view)?

    For example - if I load this view from the .xib and set its width to 300, how do I then have it resize its height to accommodate the dynamic label's new height? Do I need to use the intrinsicContentSize method to define this size?

  • Iulian Onofrei
    Iulian Onofrei about 7 years
    Why are you calling layoutSubviews twice?
  • Neko
    Neko over 6 years
    I tried it , but not work for me. can you paste a demo to GitHub? thanks a lot~
  • JackyW
    JackyW over 6 years
    @Neko Please do try out my solution listed below.
  • Kampai
    Kampai over 5 years
    layoutIfNeeded() saves the day.