Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mayoff/6201864 to your computer and use it in GitHub Desktop.
Save mayoff/6201864 to your computer and use it in GitHub Desktop.
Untested UIView subclass to be used as the custom class of a container view in a storyboard, to make that container view honor the intrinsic content size of its embedded content view.
/**
Use this as the custom class of a container view in a storyboard if you want the container view to honor its embedded view's intrinsic content size.
*/
@interface RobIntrinsicContentSizeHonoringContainerView : UIView
/** Connect this to my width constraint in the storyboard if you want me to use my subview's intrinsic content width. */
@property (nonatomic, strong) IBOutlet NSLayoutConstraint *widthConstraint;
/** Connect this to my height constraint in the storyboard if you want me to use my subview's intrinsic content height. */
@property (nonatomic, strong) IBOutlet NSLayoutConstraint *heightConstraint;
@end
#import "RobIntrinsicContentSizeHonoringContainerView.h"
@implementation RobIntrinsicContentSizeHonoringContainerView
- (void)addSubview:(UIView *)subview {
subview.translatesAutoresizingMaskIntoConstraints = NO;
[super addSubview:subview];
NSDictionary *views = NSDictionaryOfVariableBindings(subview);
if (self.widthConstraint) {
[self removeConstraint:self.widthConstraint];
self.widthConstraint = nil;
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[subview]|" options:0 metrics:nil views:views]];
}
if (self.heightConstraint) {
[self removeConstraint:self.heightConstraint];
self.heightConstraint = nil;
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[subview]|" options:0 metrics:nil views:views]];
}
}
@end
@rudolf-adamkovic
Copy link

Why not just:

- (CGSize)intrinsicContentSize {
    return [[self.subviews firstObject] intrinsicContentSize];
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment