青と紫のビューを画面の中央に配置し、緑のビューを画面の左側に配置したいと思います。
これが私のコードです:
view.backgroundColor = UIColor.orangeColor()
//Stackview:
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(stackView)
stackView.topAnchor.constraintEqualToAnchor(self.view.topAnchor).active = true
stackView.leftAnchor.constraintEqualToAnchor(self.view.leftAnchor).active = true
stackView.rightAnchor.constraintEqualToAnchor(self.view.rightAnchor).active = true
stackView.axis = UILayoutConstraintAxis.Vertical
stackView.alignment = .Center
//Blue view:
let blueBox = UIView()
stackView.addArrangedSubview(blueBox)
blueBox.backgroundColor = UIColor.blueColor()
blueBox.heightAnchor.constraintEqualToConstant(140).active = true
blueBox.widthAnchor.constraintEqualToConstant(140).active = true
//Inner stackview that contains the green view:
let greenBoxContainer = UIStackView()
let greenBox = UIView()
stackView.addArrangedSubview(greenBoxContainer)
greenBoxContainer.addArrangedSubview(greenBox)
greenBoxContainer.alignment = .Leading
//Green view:
greenBox.backgroundColor = UIColor.greenColor()
greenBox.widthAnchor.constraintEqualToConstant(120).active = true
greenBox.heightAnchor.constraintEqualToConstant(120).active = true
//Purple view:
let purpleView = UIView()
stackView.addArrangedSubview(purpleView)
purpleView.backgroundColor = UIColor.purpleColor()
purpleView.heightAnchor.constraintEqualToConstant(50.0).active = true
purpleView.widthAnchor.constraintEqualToConstant(50.0).active = true
繰り返しますが、緑のビューの左端を画面の左端に揃えるにはどうすればよいですか?
私はこれを試しました:
greenBoxContainer.widthAnchor.constraintEqualToAnchor(stackView.widthAnchor).active = true
ただし、緑のビューが画面の長さ全体に広がるだけです。