我已經創建了一個自定義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