Yawar Yawar - 4 months ago 14
Objective-C Question

Layout not changing when parent (UIView) size is changed

I have a

UIView
and inside this
UIView
I have another
UIView
, lets say parent and child
UIView
. I have set height and width of parent
UIView
to 400 in
storyboard
and set child view
constraint
to take 8px margin from top, left right and bottom from its superview.

But When I change size of parent view to 200, size of child view remain same. I have tried this in both
viewdidload
and
viewdidappear


CGRect frm = self.mainTimerView.frame;
frm.size.width = size;
frm.size.height = size;
self.mainTimerView.frame = frm;


when I change parent view to 200 child should set it self to
200-16
height and width according to constraints.

Answer

You should not mix using uiconstraint with using frame.If you want to change the size when using uiconstraint, you should make the outlet of the constraint, and then change the constraint's constant property.Call layoutIfNeeded,then you can get the right frame.

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIButton *mainTimerView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *mainTimerViewHeightConstraint;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.view layoutIfNeeded];
    NSLog(@"%@",@(self.mainTimerView.frame.size.width));

    self.mainTimerViewHeightConstraint.constant = 100;

    [self.view layoutIfNeeded];
    NSLog(@"%@",@(self.mainTimerView.frame.size.height));
}

@end

Calling layoutIfNeeded aim to to force the layout of subviews before drawing, then viewDidLayoutSubviews will be called. Note that you can get the correct frame in viewDidLayoutSubviews. In other words, you can get the right frame after viewDidLayoutSubviews has been called.

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    NSLog(@"%@",NSStringFromCGRect(self.mainTimerView.frame));
}
Comments