0
votes

I am trying to create a reusable view (xib) and use it in my storyboard with autolayout. The problem is that it does not seem to use the constraints that I have set up on the storyboard for it.

So my realy basic IOS-project contains:

  • MyView.swift
  • MyView.xib
  • Main.storyboard
  • ViewController.swift

The MyView class is connected to the xib file in the proper manner:

import UIKit

class MyView: UIView {

    @IBOutlet var View: UIView!

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        NSBundle.mainBundle().loadNibNamed("MyView", owner: self, options: nil)
        self.addSubview(self.View);
    }
}

In my storyboard i added a UIView (CustomClass=MyView) with 2 simple height/width constraints. When I run the app the view is not sized according to those constraints. It is rendered with the height/width properties in the xib.

Does anyone have a clue on how to make my custom view conform to my constraints that I set up in my storyboard?

2

2 Answers

0
votes

Are you saying that your UIView is rendered with the height and width of the xib when you load it's view with the xib? Meaning like, the xib is the only thing you see when you run the simulator? If so, I think the simple solution is to create an additional UIView that loads the xib. Make the NewView a subview of MyView That way you have MyView -> NewView(loaded with xib).

Sorry if that is way off. It is just a little difficult to get what you mean without seeing it. Maybe throw up a screenshot or two. Would have posted this as a comment and not an answer but I don't have the reputation yet.

0
votes

this should help

var contentView =  NSBundle.mainBundle().loadNibNamed("MyView", owner: self, options: nil)
contentView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addSubview(contentView)

    var constTop:NSLayoutConstraint = NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0);
    self.view.addConstraint(constTop);

    var constBottom:NSLayoutConstraint = NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0);
    self.view.addConstraint(constBottom);

    var constLeft:NSLayoutConstraint = NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0);
    self.view.addConstraint(constLeft);

    var constRight:NSLayoutConstraint = NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0);
    self.view.addConstraint(constRight);