Reputation: 1867
I'm trying to create a card view that flips based on this tutorial. It creates a UIView and adds the card view.
For this I created a custom UIView (with Xib) and so far it works fine. I've added the correct constraints in my Storyboard for the view on which addSubview is called. This is working so far, but when I add the custom UIView it refers to its size in the xib and not the size of the superview.
How can I add the necessary Autolayout constraints to make the subview fit into its superview?
Thanks!
P.S. I've written it in Objective-C but it doesn't matter to me, if the answer is in swift or Objective-C.
Upvotes: 3
Views: 3263
Reputation: 1466
Not sure, what wrong is there. I did the same thing in following way:
1) ProductItemView, a sub class of UIView and created ProductItemView.xib which is having a UIView object.
2) In .xib set File's owner class to ProductItemView so that UIView object of .xib and other subviews can be loaded and linked with IBOutlet.(see image)
3) In init method (initWithFrame: in my case) method put below code
NSArray *nibViewArray = [[NSBundle mainBundle] loadNibNamed:@"ProductItemView" owner:self options:nil];
if (nibViewArray.count) {
UIView *nibView = [nibViewArray objectAtIndex:0];
[self addSubview:nibView];
nibView.translatesAutoresizingMaskIntoConstraints = NO;
NSDictionary *viewDict = NSDictionaryOfVariableBindings(nibView);
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[nibView]-0-|" options:0 metrics:nil views:viewDict]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[nibView]-0-|" options:0 metrics:nil views:viewDict]];
}
and finally create object of ProdutItemView and with frame or set Constraints and add it to super view. If you are setting constraint then do not forget to set translatesAutoresizingMaskIntoConstraints property to NO. Hope it will be helpful for you.
Upvotes: 3
Reputation: 877
if you want to do it in code. seems to work out better for me and makes more sense.
// make sure myCustomView is added to the superview
// and ignore the layout guides if the superview is not your view controller
[myCustomView setTranslatesAutoresizingMaskIntoConstraints: NO];
id topGuide = self.topLayoutGuide;
id bottomGuide = self.bottomLayoutGuide;
NSDictionary * viewsDictionary = NSDictionaryOfVariableBindings(myCustomView, topGuide, bottomGuide);
[mySuperiew addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[myCustomView]|" options:0 metrics: 0 views:viewsDictionary]];
[mySuperiew addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[topGuide][myCustomView][bottomGuide]|" options:0 metrics: 0 views:viewsDictionary]];
Upvotes: 0