我创建了一个从XIB文件加载的自定义UIView。然后我将视图添加到stackview,并在项目上设置宽度约束。
如果我从故事板上做到这一点,那就完美了,但是如果我从Swift那里做到这一点,我就无法让视图延伸到约束。 stackview为视图分配空间,但视图不会延伸到空间。
自定义视图快速代码:
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)的viewcontroller:
@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能够"忽略"它的框架并根据stackview的高度和宽度约束我的设置调整大小。
我错过了什么?
更新:
我对自定义视图的约束(基本上只是带有标签的视图 - 但我打算将它用于更复杂的布局):
答案 0 :(得分:1)
试试这个:
let widthConstraint = NSLayoutConstraint (item: your_item_here, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: your_value_here)
self.view.addConstraint(widthConstraint)
答案 1 :(得分:0)
至少应该使用sizeThatFits:定义自定义视图的大小 。不幸的是,我无法看到你的布局限制来判断它们是否合适。
答案 2 :(得分:0)