2017-02-01 7 views
0

私はtestView UIViewとtestviewSubという名前のサブビューを持っています。 testViewはNSLayoutConstraintを使用して制約されています。そして私はtestView.boundsにsubViewフレームを設定しました。しかし、それは動作しません。ここでは、コードNSLayoutConstraint - サブビューフレームを親ビューの境界に設定できません

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にの枠を設定している場合。できます。

答えて

0

レイアウトはどこにありますか?私は、ビューが現れるまで制約が有効にならない前に問題にぶつかりました。したがって、フレームが正しいサイズになるようにviewDidLoadまたはviewWillAppearにすると問題が発生します。

この場合、viewDidAppeartestViewSubを追加すると、私はそれが私がお勧めする方法であるかどうかはわかりませんが、私にとってはうまくいっています。ちょうどtestViewと同じように、それをレイアウトする制約を使用して、またviewDidLoadまたはviewWillAppearから動作します:

// 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 

これは、単にフレームを設定するよりも良い回転に対処します。

関連する問題