I have created a custom UIView which is loaded from an XIB file. I am then adding the view to a stackview, and setting a width constraint on the item.
It's working perfectly if I do this from the storyboard, however if I'm doing it from Swift, I can't get the view to stretch to the constraint. The stackview is allocating space for the view, but the view doesn't stretch to the space.
Custom view swift code:
import Foundation
import UIKit
@IBDesignable class TabButton: UIView {
@IBOutlet weak var label: UILabel!
@IBInspectable var TabText: String? {
get {
return label.text
}
set(TabText) {
label.text = TabText
label.sizeToFit()
}
}
override func intrinsicContentSize() -> CGSize {
return CGSize(width: UIViewNoIntrinsicMetric, height: UIViewNoIntrinsicMetric)
}
override init(frame: CGRect) {
// 1. setup any properties here
// 2. call super.init(frame:)
super.init(frame: frame)
// 3. Setup view from .xib file
xibSetup()
}
required init(coder aDecoder: NSCoder) {
// 1. setup any properties here
// 2. call super.init(coder:)
super.init(coder: aDecoder)!
// 3. Setup view from .xib file
xibSetup()
}
// Our custom view from the XIB file
var view: UIView!
func xibSetup() {
view = loadViewFromNib()
// use bounds not frame or it'll be offset
view.frame = bounds
// Make the view stretch with containing view
view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
// Adding custom subview on top of our view (over any custom drawing > see note below)
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "TabButton", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
self.roundCorners([.TopLeft, .TopRight], radius: 10)
return view
}
}
And this is the viewcontroller that is adding the view (tabButton) to the stackview (tabBar):
@IBOutlet weak var tabBar: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
let tabButton = TabButton(frame: CGRectZero)
tabButton.label.text = "All Videos"
tabButton.backgroundColor = UIColor.blackColor()
let widthConstraint = NSLayoutConstraint(item: tabButton, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100)
tabButton.addConstraint(widthConstraint)
tabBar.insertArrangedSubview(tabButton, atIndex: 0)
}
I want the tabButton to "ignore" it's frame and resize according to the height of the stackview and the width constraint I'm setting.
What am I missing?
UPDATE:
My constraints on the custom view (basically just a view with a label - But I plan to use this with more complex layouts as well):