我已经创建了一个自定义UIView从XIB文件加载。然后,我将视图添加到堆栈视图,并为该项目设置宽度约束。Swift:自定义UIView不调整约束
如果我从故事板上做到这一点,它的工作是非常完美的,但是如果我是从Swift开始做的话,我无法将视图拉伸到约束条件。堆栈视图为视图分配空间,但视图不会伸展到空间。
自定义视图SWIFT代码:
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
}
}
这是添加视图(tabButton)到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)
}
我想tabButton为“忽略“它的框架和根据堆栈视图的高度和我设置的宽度约束来调整大小。
我错过了什么?
UPDATE:
我的自定义视图约束(基本上只是带有标签的观点 - 但是我计划更复杂的布局,以及使用此):
要以编程方式添加约束,是吗? –
是的,因为视图是以编程方式添加的。 – Whooper