繁体   English   中英

NSLayoutConstraint-无法将子视图框架设置为父视图范围

[英]NSLayoutConstraint - can't set subview frame to parent view bounds

我有一个testView UIView和名为testViewSub的子视图。 使用NSLayoutConstraint限制了NSLayoutConstraint 我将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的框架。 有用。

布局在哪里发生? 在出现约束之前,我一直遇到问题,直到视图出现,约束才生效,因此依赖于viewWillAppearviewDidLoadviewWillAppear的正确大小会引起问题。

在这种情况下,在viewDidAppear添加testViewSub对我testViewSub ,尽管我不确定这是我推荐的方式。 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

与简单地设置框架相比,这还将更好地处理旋转。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM