使用xib

时间:2016-04-16 12:34:21

标签: ios swift interface-builder custom-controls xib

我正在尝试创建自定义可重用视图,让我们说QuestionView。现在我使用this class来扩展QuestionView,因此它会从我的xib加载视图,然后将此视图作为子视图添加到self。如果我的视图具有恒定的高度和宽度,它可以正常工作,但我需要这种布局

Question View xib

此视图的文件所有者设置为QuestionView

我的标签在顶部通过约束与顶部,左侧和右侧相连,但它在高度方面很灵活 - 标签是多线的。是/否按钮视图连接到标签的底部,超视图的左侧和右侧,并且具有恒定的高度。按钮视图底部连接到左侧和右侧的详细信息视图具有恒定高度。所以我的QuestionView具有灵活的高度。例如,如果我将标签文本更改为2行,则应该拉伸我的视图。

我有ViewController xib,我将通用视图设置为QuestionView

我只是将此视图添加为QuestionView的子视图,所以我认为视图和子视图之间存在约束问题,我应该添加它们吗?我尝试在它们之间添加左,右,顶部,底部约束,translatesAutoresizingMaskIntoConstraints设置为false,但无论如何都是奇怪的(类似于xibs的高度)superview(QuestionView)height,子视图高度是好在运行时

那我在这里做错了什么?我是否需要以不同的方式将子视图高度绑定到超视图高度?

UPD 即可。这是运行时的截图,灰色视图是它在运行时的大小,应该被拉伸到TextField底部。现在看起来它是运行时ok子视图高度的错误效果。

Runtime

这是我现在的代码

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
    }

}

1 个答案:

答案 0 :(得分:0)

首先,你必须在QuestionView和它的超级视图底部之间添加一个约束

其次,看起来像问题可能是QuestionView的superview及其父约束。

<强> UPD

确定这类错误的最佳工具 - Reveal