Anuj Rajput Anuj Rajput - 1 year ago 76
iOS Question

Resize a superview to make its size equal to the the size of its subviews

I have subclassed a UIView and created few views inside it. I want to create an instance of this view inside my view controller's view and there's another custom view which will be placed below that view. I am not sure how do I put the second view below my first view.

When I debug the frames, I get {{0,0}, {0,0}}. I am using Masonry for view layout. I have tried several solutions from this thread

I have created a sample project which has the actual code I have tried.

In this sample project, there are 2 subclasses of

and a view controller
which creates objects from both these views. I need to perfectly order them in such a way they are perfectly aligned vertically (

Am I doing something wrong? Is there a right way to subclass a UIView and then refer it in the controller?

This is how the view should look like


Answer Source

When you are using AutoLayout, and you want the parent view to resize according to I'ts subclasses, It needed to know how big the content is.

The most top view has to have a constraint to the top of the parent view. And the most bottom view has to have a constraint to the bottom of the parent view.

Currently your views are acutely not containing there subclasses.

If you will try, for instance to set the background color of "topView" to red, You will notice, It does not change I'ts color. That is because I'ts size is 0. I'ts not wrapping I'ts content. If you will set "clipToBound" to YES, you will not see Its subclasses too.

To fix it, add a bottom constraint, from the bottom view to the parent view:

[self.subtitleTextLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.mas_bottom); //This line is added

[self.sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.mas_bottom); // This line is added