I'm trying to break up my view controller content into smaller chunks of single views that I load from xib. I'm doing that by placing placeholder UIView objects into my Storyboard view controllers and use them to add the actual UIView subclass that I have laid out in a xib file as a subview at build time.
The process is pretty straightforward and was discussed before.
The problem, however, is that the AutoLayout constraints, defined in the xib file, are not working when I add the view.
To illustrate the problem, I've created a sample project: A ViewController has a colorView of type CustomColorView (subclass of UIView) that will be added to a plain UIView placeholder. The CustomColorViewclass then has a property of coloredView which should fill the out the whole space (defined by AutoLayout constraints to every side in the xib file).
NibLoadable protocol:
public protocol NibLoadable {
static var nibName: String { get }
}
public extension NibLoadable where Self: UIView {
public static var nibName: String {
return String(describing: Self.self)
}
public static var nib: UINib {
let bundle = Bundle(for: Self.self)
return UINib(nibName: Self.nibName, bundle: bundle)
}
func setupFromNib() {
guard let loadedView = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
loadedView.frame = bounds
addSubview(loadedView)
loadedView.translatesAutoresizingMaskIntoConstraints = false
loadedView.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
loadedView.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
loadedView.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
loadedView.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
}
}
When I add my custom view to the plain UIView, I would assume that it applies all the defined constraints from the nib file but it doesn't. The print result should be the same for both view but they are different (coloredView still has it's size from the xib file).
Any ideas on what might go wrong? Thanks for your help!
The whole project is up on GitHub: XibAutoLayoutExample

