Eri*_*ric 5 uikit ios autolayout uistackview
我想将蓝色和紫色视图对齐到屏幕的中心,我想将绿色视图对齐到屏幕的左边:
这是我的代码:
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
Run Code Online (Sandbox Code Playgroud)
要重复一遍,如何将绿色视图的左边缘与屏幕的左边缘对齐?
我尝试了这个:
greenBoxContainer.widthAnchor.constraintEqualToAnchor(stackView.widthAnchor).active = true
Run Code Online (Sandbox Code Playgroud)
但只会将绿色视图延伸到整个屏幕长度。
一种方法是添加间隔视图:
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
Run Code Online (Sandbox Code Playgroud)
请注意,我不再设置 的greenBoxContainer对齐方式,因此它默认为.Fill. 因此, 的右边缘spacer被刷新到内部 stackview 的右边缘,并且它占据了所有宽度,greenBox只留下足够的空间来满足其宽度约束。
但这是一种解决方法,我希望能够指定对齐方式而不必创建间隔视图。
| 归档时间: |
|
| 查看次数: |
1230 次 |
| 最近记录: |