我有四个需要水平居中的元素的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!)
答案 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比需要的大,我把它的大小和它的超级视图相同,它解决了问题。