Swift:如何在垂直stackview

时间:2017-06-28 19:08:41

标签: ios swift uistackview

我有四个需要水平居中的元素的stackview:

let stackView = UIStackView()
stackView.axis = UILayoutConstraintAxis.vertical
stackView.distribution  = UIStackViewDistribution.equalSpacing
stackView.alignment = UIStackViewAlignment.center
stackView.spacing = 5.0
stackView.addArrangedSubview(browseButton)
stackView.addArrangedSubview(orLabel)
stackView.addArrangedSubview(createButton)
stackView.addArrangedSubview(imageView)
let imageViewCenterXConstraint = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: stackView, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
stackView.addConstraint(imageViewCenterXConstraint)
stackView.translatesAutoresizingMaskIntoConstraints = false

let stackViewCenterXConstraint = NSLayoutConstraint(item: stackView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: wantMorePage!, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
let stackViewCenterYConstraint = NSLayoutConstraint(item: stackView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: wantMorePage!, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)
wantMorePage?.backgroundColor = UIColor.gray

wantMorePage!.addSubview(stackView)

wantMorePage!.addConstraint(stackViewCenterXConstraint)
wantMorePage!.addConstraint(stackViewCenterYConstraint)

self.scrollView.addSubview(wantMorePage!)

我添加了约束并将对齐设置为居中,但元素仍未居中(屏幕截图)。我该怎么做才能让他们居中?enter image description here

2 个答案:

答案 0 :(得分:0)

替换:

wantMorePage!.addConstraint(stackViewCenterXConstraint)
wantMorePage!.addConstraint(stackViewCenterYConstraint)

使用:

stackViewCenterXConstraint.isActive = true
stackViewCenterYConstraint.isActive = true

https://developer.apple.com/documentation/uikit/uiview/1622523-addconstraint

此外,您需要先添加子视图,然后才能向其添加约束

将此动作移到isActive调用上方:

self.scrollView.addSubview(wantMorePage!)

像这样:

wantMorePage!.addSubview(stackView)
self.scrollView.addSubview(wantMorePage!)

let imageViewCenterXConstraint = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: stackView, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
imageViewCenterXConstraint.isActive = true

let stackViewCenterXConstraint = NSLayoutConstraint(item: stackView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: wantMorePage!, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
let stackViewCenterYConstraint = NSLayoutConstraint(item: stackView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: wantMorePage!, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)

stackViewCenterXConstraint.isActive = true
stackViewCenterYConstraint.isActive = true

答案 1 :(得分:0)

发现问题是什么 - 视图的宽度不正确,在我的代码中,wantMorePage比需要的大,我把它的大小和它的超级视图相同,它解决了问题。