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

问题描述 投票:-1回答:2

如何在Superview底部附加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视图。

ios swift xcode uikit xib
2个回答
1
投票

您可以通过将constraintsframe设置为xibView来实现此目的。

设置约束:

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位置和宽度,高度。


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
}
© www.soinside.com 2019 - 2024. All rights reserved.