rutruth
rutruth

Reputation: 790

Programmatic layout : UIStackView alignment doesn't seem to work

I have created a UIViewController with a UIStackView (vertical axis) wrapped in a UIScrollView that's pinned to the edges of the root View with auto-layout constraints.

I have also generated a number of UIButtons and added to the arranged subviews of the UIStackView.

I have tried to no avail to centre align the UIButtons in the UIStackView.

I'm not certain what i'm doing wrong.

Here's the code:

import UIKit

class ViewController: UIViewController {
var scrollView: UIScrollView!
var stackView: UIStackView!

override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundColor = UIColor.whiteColor()

    scrollView = UIScrollView()
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(scrollView)

    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[scrollView]|", options: .AlignAllCenterX, metrics: nil, views: ["scrollView": scrollView]))
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[scrollView]|", options: .AlignAllCenterX, metrics: nil, views: ["scrollView": scrollView]))


    stackView = UIStackView()
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.axis = .Vertical
    stackView.alignment = .Center
    scrollView.addSubview(stackView)

    scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[stackView]|", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: ["stackView": stackView]))
    scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[stackView]|", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: ["stackView": stackView]))

    for _ in 1 ..< 100 {
        let vw = UIButton(type: UIButtonType.System)
        vw.setTitle("Button", forState: .Normal)
        stackView.addArrangedSubview(vw)
    }
}

}

Upvotes: 0

Views: 722

Answers (2)

rutruth
rutruth

Reputation: 790

An extra equal width constraint between the scrollView and the stackView was needed. Like this:

scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[stackView(==scrollView)]", options: .AlignAllCenterX, metrics: nil, views: ["stackView": stackView, "scrollView": scrollView]))

That did it for me.

Upvotes: 2

Maciek Czarnik
Maciek Czarnik

Reputation: 6191

How about:

stackView.Alignment = UIStackViewAlignment.Center

?

Upvotes: 0

Related Questions