2016-06-28 11 views
0

Ich habe eine UIViewController mit einer UIStackView (vertikale Achse) in einem UIScrollView gewickelt, die an den Rändern der Wurzel View mit Auto-Layout-Einschränkungen festgesteckt ist.Programmatic Layout: UIStackView Ausrichtung scheint nicht zu arbeiten

Ich habe auch eine Reihe von UIButton s generiert und die arranged subviews der UIStackView hinzugefügt.

Ich habe vergeblich versucht, die UIButtons in der UIStackView zu zentrieren.

Ich bin mir nicht sicher, was ich falsch mache.

Hier ist der 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) 
    } 
} 

} 

Antwort

2

Zwischen der und der stackView wurde eine zusätzliche Gleichbreitenbeschränkung benötigt. Wie folgt:

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

Das war es für mich.

0

Wie wäre:

stackView.Alignment = UIStackViewAlignment.Center 

?

+0

Das habe ich schon gemacht. Ich gehe davon aus, dass ich etwas falsch mache. – kooldave98