Anuj Rajput Anuj Rajput - 3 months ago 20
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.
https://github.com/anuj-rajput/ViewSample

In this sample project, there are 2 subclasses of

UIView
,
PhoneVerificationTopView
and
PhoneVerificationPhoneNumberView
and a view controller
PhoneVerificationViewController
which creates objects from both these views. I need to perfectly order them in such a way they are perfectly aligned vertically (
PhoneNumberView
below
TopView
).

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

Screenshot

Answer

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.centerX.equalTo(self.titleTextLabel);
            make.width.equalTo(self.mas_width).multipliedBy(0.7);
            make.top.equalTo(self.titleTextLabel.mas_bottom).with.offset(10.f);
            make.bottom.equalTo(self.mas_bottom); //This line is added
        }];


[self.sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self);
            make.width.equalTo(self).multipliedBy(0.4);
            make.height.equalTo(@40);
            make.top.equalTo(self.phoneNumberTextView.mas_bottom).with.offset(30.f);
            make.bottom.equalTo(self.mas_bottom); // This line is added
        }];