UIStackview具有不同对齐的子视图

时间:2015-12-15 17:03:30

标签: ios autolayout uikit uistackview

我想将蓝色和紫色视图对齐到屏幕中央,我想将绿色视图对齐到屏幕左侧:

enter image description here

这是我的代码:

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

但它只能通过屏幕的长度拉伸绿色视图。

1 个答案:

答案 0 :(得分:1)

一种方法是添加间隔视图:

let greenBox = UIView()
stackView.addArrangedSubview(greenBoxContainer)
greenBoxContainer.addArrangedSubview(greenBox)

let spacer = UIView()
greenBoxContainer.addArrangedSubview(spacer)
spacer.rightAnchor.constraintEqualToAnchor(greenBoxContainer.rightAnchor).active = true

greenBoxContainer.widthAnchor.constraintEqualToAnchor(stackView.widthAnchor).active = true
greenBox.backgroundColor = UIColor.greenColor()
greenBox.widthAnchor.constraintEqualToConstant(120).active = true
greenBox.heightAnchor.constraintEqualToConstant(120).active = true

请注意,我不再设置greenBoxContainer的对齐方式,因此默认为.Fill。因此,spacer的右边缘被刷新到内部stackview的右边缘,它占据了所有宽度,只留下greenBox足以满足其宽度约束的空间。

但这是一种解决方法,我希望能够指定对齐而无需创建间隔视图。