6

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

在此处输入图像描述

这是我的代码:

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

但它只会将绿色视图延伸到屏幕的长度。

4

1 回答 1

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被刷新到内部堆栈视图的右侧边缘,并且它占据了所有宽度,留下greenBox足够的空间来满足其宽度约束。

但这是一种解决方法,我希望能够指定对齐方式而不必创建间隔视图..

于 2015-12-15T18:13:56.980 回答