在Swift中以编程方式设置XIB文件的约束

时间:2019-03-14 14:44:55

标签: ios swift xcode uikit xib

如何在超级视图的底部附加XIB文件

我有一个名为“ xibFIleView”的XIB文件

enter image description here

我用于调用XIB View的代码是:-

 override func viewDidLoad() {
        super.viewDidLoad()

       self.view.addSubview(instanceFromNib())
    }

    func instanceFromNib() -> xibFIleView {

        return UINib(nibName: "xibFileView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! xibFIleView
    }
}

当我运行项目时,我的模拟器显示: enter image description here

我们如何在超级视图的底部附加XIB视图。

2 个答案:

答案 0 :(得分:1)

您可以通过将constraints设置为framexibView来实现。

设置约束:

override func viewDidLoad() {
    super.viewDidLoad()

    let xibView = instanceFromNib()
    self.view.addSubview(xibView)
    xibView.translatesAutoresizingMaskIntoConstraints = false
    let constraint_leading = NSLayoutConstraint(item: xibView, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 0)
    let constraint_bottom = NSLayoutConstraint(item: xibView, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: 0)
    let constraint_height = NSLayoutConstraint(item: xibView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: xibView.frame.height)
    let constraint_width = NSLayoutConstraint(item: xibView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: xibView.frame.width)
    self.view.addConstraint(constraint_leading)
    self.view.addConstraint(constraint_bottom)
    xibView.addConstraint(constraint_height)
    xibView.addConstraint(constraint_width)
}

-----或-----

设置框架:

在您的viewDidLoad()中进行以下更改:

override func viewDidLoad() {
    super.viewDidLoad()

    let xibView = instanceFromNib()
    let y_pos = self.view.frame.height - xibView.frame.height
    xibView.frame = CGRect(x: 0, y: y_pos, width: xibView.frame.width, height: xibView.frame.height)
    // change x, y, width, height based on your requirement.
    self.view.addSubview(xibView)
}

注意:根据您的要求更改x,y的位置和宽度,高度。

答案 1 :(得分:0)

使用自动布局添加4个约束,足以指定子视图的宽度,高度,x和y位置。例如:

override func viewDidLoad() {
    super.viewDidLoad()

    let child = instanceFromNib()
    self.view.addSubview(child)
    NSLayoutConstraint.activate([
        child.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        child.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        child.trailingAnchor.constraint(equalTo: view.trailingAnchor),
        child.heightAnchor.constraint(equalToConstant: 300) // <- Your desired view height here
    )]
}

func instanceFromNib() -> xibFIleView {

    return UINib(nibName: "xibFileView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! xibFIleView
}