I'm trying to create reusable views in a xib/nib file in swift iOS 10.
When I create a stack view and have 2 objects in it and make sure my stackview is constrained to the container view of the nib/xib (top to top, bottom to bottom, leading to leading and finally trailing to trailing), I get an error saying I'm missing my Y position for the first and the second object. Creating just one of them usually fixes it. Although this is where things to go sideways. In all my previous research, I shouldn't need to do this if I have my distribution of my stackview to Fill. Although this seems to quiet Xcode, it creates a over constraint issue when I try to run my program.
Here is what I used to load my nib in a view from my main storyboard :
public protocol NibOwnerLoadable: class {
static var nib: UINib { get }
}
//MARK:- Generic Implementation
public extension NibOwnerLoadable {
// Use the xib file with the same name as your UIView subclass located in the bundle of that class
static var nib: UINib {
return UINib(nibName: String(describing: self), bundle: Bundle(for: self))
}
}
//MARK:- Support for instation from the XIB file
public extension NibOwnerLoadable where Self: UIView {
// Function to load content and constraints automatically
func loadNibContent() {
let layoutAttributes: [NSLayoutAttribute] = [.top, .leading, .bottom, .trailing]
for view in Self.nib.instantiate(withOwner: self, options: nil) {
if let view = view as? UIView {
view.translatesAutoresizingMaskIntoConstraints = false
view.frame = bounds
self.addSubview(view)
layoutAttributes.forEach{ attribute in self.addConstraint(NSLayoutConstraint(item: view, attribute: attribute, relatedBy: .equal, toItem: self, attribute: attribute, multiplier: 1, constant: 0.0))
}
}
}
}
}
I know my issue is an extra constraint being added by Auto Layout but why and where. This other question is very close to what I'm trying to do but for some reason my AutoLayout knowledge is a jumbled in my head. Adding a subclassed UIView to a Nib with its auto layout constraints A little help would be appreciate. Please explain the why, not just how to do it. I'm a guy who likes to understand the back story. It makes it logical and easier to retain.
Here are pictures of my filterView as a nib/xib that is loaded inside searchAndFilterView as FilterView (UIView) that is loaded inside one my view controller inside my storyboard. Think reusable Tool Views.