0

I have a storybaord with a UIView that has a class set to MyView (this class is defined as @interface MyView : UIView).

In class MyView, I have this construction:

-(void)awakeFromNib{            

    [super awakeFromNib];

    [[UINib nibWithNibName:@"MyNib" bundle:nil] instantiateWithOwner:self options:nil];

    [self addSubview:self.contentView];
}    

It loads design from nib and add contentView to it. Now, how can I set contentView width to be the same as width of self? I have tried add constraint programatically under addSubview method, but app crashed.

So where should I add constraint and how the code should be?

Martin Perry
  • 9,232
  • 8
  • 46
  • 114

2 Answers2

1

You don't have to set constraints to make the width equal.

Just set the constraints for the elements in the xib so that they will get aligned according to their superview frame.

And you can set the xib view frame in the awakeFromNib method.

Teja Nandamuri
  • 11,045
  • 6
  • 57
  • 109
0

You can make outlet of your xib view and then can set set constraints to programatically view accordingly to its parent view. you might have get idea from this It should work.

Community
  • 1
  • 1
T.Ratzz
  • 71
  • 8
  • I have used this approach, but it crashed... I am not sure where I should add constraint, because in awakeFromNib, crash happens. – Martin Perry Oct 09 '16 at 14:29
  • I am agree with @teja Nandamuri actually you can set your constraints in xib view and then in viewDidAppeare method you can add your child view with same width of your parent view frame width as constrains are execute after viewWillAppeare. – T.Ratzz Oct 10 '16 at 05:53