Sowmia Sundararajan
Sowmia Sundararajan

Reputation: 1623

AutoLayout for Views Generated Programmatically

Having two views headerView and footterView. I want the views to be placed one below another. i mean to say headerView on top and footerView below headerView.

UIView *mainview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    headerView =  [[[NSBundle mainBundle] loadNibNamed:@"BaseHeader" owner:self options:nil] objectAtIndex:0];
    footterView = [[[NSBundle mainBundle] loadNibNamed:@"BaseFotter" owner:self options:nil] objectAtIndex:0];

 self.view = mainview;
 [mainview  addSubview:headerView];
 [mainview  addSubview:footterView];

I have tried adding constraint as below

NSDictionary *viewsDictionary =
NSDictionaryOfVariableBindings(headerView,footterView);

NSLayoutConstraint *constraint = [[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[headerView]-[footterView]|" options:0 metrics:nil views:viewsDictionary] objectAtIndex:0];

NSLayoutConstraint *mconstraint = [[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[headerView(==footterView)]|" options:0 metrics:nil views:viewsDictionary] objectAtIndex:0];

[mainview addConstraint:constraint];
[mainview addConstraint:mconstraint];

But always the footerView alone is displayed in screen. If i add View in below order , always HeaderView is displayed.

[mainview  addSubview:footterView];
[mainview  addSubview:headerView];

AutoLayout is checked in both xib (BaseHeader.xib & BaseFotter.xib ). do i need to do any more in xib?

Upvotes: 3

Views: 335

Answers (1)

Niraj
Niraj

Reputation: 171

Change your constraints adding code to:

NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[headerView]-[footterView]|" options:0 metrics:nil views:viewsDictionary];

NSArray *mconstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[headerView(==footterView)]|" options:0 metrics:nil views:viewsDictionary];

[mainview addConstraints: constraints]; [mainview addConstraints:mconstraints];

Upvotes: 1

Related Questions