【发布时间】:2016-08-08 10:27:53
【问题描述】:
我正在尝试创建自定义可重用视图,比如说QuestionView。现在我使用this class 由我的QuestionView 扩展,所以它从我的xib 加载视图,然后这个视图作为子视图添加到self。如果我的视图具有恒定的高度和宽度,它可以正常工作,但我需要这种布局
此视图的文件所有者设置为QuestionView。
我在顶部有标签,它通过约束与顶部、左侧和右侧连接,但它在高度方面很灵活 - 标签是多行的。是/否按钮视图连接到标签底部,超级视图的左侧和右侧,并且具有恒定的高度。连接到按钮视图底部的详细信息视图,向左和向右,具有恒定的高度。所以我的QuestionView 有灵活的高度。例如,如果我将标签文本更改为 2 行,我的视图应该被拉伸。
我有 ViewController xib,我在其中放置通用视图并将其类设置为 QuestionView。
我只是将此视图添加为QuestionView 的子视图,所以我认为视图和子视图之间的约束存在问题,我应该添加它们吗?我尝试在 translatesAutoresizingMaskIntoConstraints 设置为 false 的情况下在它们之间添加左、右、上、下约束,但无论如何都变得奇怪(类似于 xibs 的高度) superview(QuestionView) 高度,运行时子视图高度正常。
那么我在这里做错了什么?我是否需要以不同的方式将子视图高度绑定到父视图高度?
UPD。这是运行时的屏幕截图,灰色视图是运行时的大小,应该拉伸到 TextField 底部。现在看起来它是运行时 ok 子视图高度的错误效果。
这是我的代码
import UIKit
protocol NibDefinable {
var nibName: String { get }
}
@IBDesignable
class NibLoadingView: UIView, NibDefinable {
var containerView: UIView!
var nibName: String {
return String(self.dynamicType)
}
override init(frame: CGRect) {
super.init(frame: frame)
nibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
nibSetup()
}
private func nibSetup() {
//clipsToBounds = true
containerView = loadViewFromNib()
containerView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(containerView)
addConstraint(.Top)
addConstraint(.Left)
addConstraint(.Bottom)
addConstraint(.Right)
}
private func addConstraint(attribute: NSLayoutAttribute) {
self.addConstraint(NSLayoutConstraint(item: self,
attribute: attribute,
relatedBy: .Equal,
toItem: containerView,
attribute: attribute,
multiplier: 1,
constant: 0.0
))
}
private func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: nibName, bundle: bundle)
let nibView = nib.instantiateWithOwner(self, options: nil).first as! UIView
return nibView
}
}
【问题讨论】:
-
您能否提供运行时布局的图片。你的描述很难理解
-
是的,您必须将 translatesAutoresizingMaskIntoConstraints 设置为 false 并在 nibSetup() 处添加四个侧面约束
标签: ios swift interface-builder custom-controls xib