NSLayoutConstraint - 无法将子视图帧设置为父视图边界

时间:2017-02-01 15:48:11

标签: ios uiview swift3 nslayoutconstraint

我有一个testView UIView和一个名为testViewSub的子视图。使用NSLayoutConstraint约束testView。我将subView框架设置为testView.bounds。但它不起作用。这是代码

let testView = UIView()
    testView.backgroundColor = UIColor.red

    self.view.addSubview(testView)

    testView.translatesAutoresizingMaskIntoConstraints = false


    NSLayoutConstraint(item: testView, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: 30).isActive = true

    NSLayoutConstraint(item: testView, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1.0, constant: -30).isActive = true

    NSLayoutConstraint(item: testView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1.0, constant: 200).isActive = true

    NSLayoutConstraint(item: testView, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 0.15, constant: 0).isActive = true




    let testViewSub = UIView()
    testViewSub.backgroundColor = UIColor.green
    testViewSub.frame = testView.bounds
    self.testView.addSubview(testViewSub)

    testViewSub.translatesAutoresizingMaskIntoConstraints = false

但是如果我使用CGRect设置testView的帧。有用。

1 个答案:

答案 0 :(得分:0)

布局在哪里发生?在问题出现之前约束没有生效之前我遇到了问题,所以在viewDidLoadviewWillAppear中依赖于框架的正确尺寸会导致问题。

在这种情况下,在testViewSub中添加viewDidAppear对我有用,虽然我不确定这是我推荐的方式。与testView一样,使用约束进行布局也适用于viewDidLoadviewWillAppear

    // layout constraints however you want - in this case they are such that green view's frame = red view's bounds

    let testViewSub = UIView()
    testViewSub.backgroundColor = UIColor.green
    self.testView.addSubview(testViewSub)

    NSLayoutConstraint(item: testViewSub, attribute: .leading, relatedBy: .equal, toItem: testView, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true

    NSLayoutConstraint(item: testViewSub, attribute: .trailing, relatedBy: .equal, toItem: testView, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true

    NSLayoutConstraint(item: testViewSub, attribute: .top, relatedBy: .equal, toItem: testView, attribute: .top, multiplier: 1.0, constant: 0).isActive = true

    NSLayoutConstraint(item: testViewSub, attribute: .height, relatedBy: .equal, toItem: testView, attribute: .height, multiplier: 1.0, constant: 0).isActive = true


    testViewSub.translatesAutoresizingMaskIntoConstraints = false

这也比简单地设置框架更好地处理旋转。