Center views horizontally of different widths inside a UIStackView
Asked Answered
G

4

7

I would like to setup a UIViewStack so that it will center the two views inside, even though they have different widths. Here is an example:

example

Is it possible to achieve this type of configuration with UIStackView? I cannot seem to figure it out!

Any help would be appreciated.

Gautama answered 8/11, 2017 at 0:17 Comment(0)
T
8

You should use nested StackView. Firstly embed View1 and View2 in a Horizontal StackView. Set alignment property center and distribution fill-proportionally. Then embed the Horizontal StackView in a Vertical Stackview. Here I have attached my demo screenshot: enter image description here

Thorpe answered 8/11, 2017 at 1:32 Comment(0)
P
2

No , you can't . From the apple's Doc

The stack view uses Auto Layout to position and size its arranged views. The stack view aligns the first and last arranged view with its edges along the stack’s axis. In a horizontal stack, this means the first arranged view’s leading edge is pinned to the stack’s leading edge, and the last arranged view’s trailing edge is pinned to the stack’s trailing edge.

You can use Constraints instead.

Publicspirited answered 8/11, 2017 at 1:26 Comment(0)
J
1

I can make UIStackView auto grow width after adding views there

  1. Create UIViewController and give UIStackView be center there enter image description here
  2. Constraint StackView.leading Priority set to 250 to avoid warning issue in xib enter image description here
  3. Codes

    class StackSampleViewController: UIViewController {

    @IBOutlet weak var stackView: UIStackView!
    
    //Keep center auto grow with subviews
    @IBAction func touchUpAdd(_ sender: Any) {
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
    
        if (stackView.subviews.count % 2) == 0 {
            view.widthAnchor.constraint(equalToConstant: 100).isActive = true
            view.backgroundColor = .black
        } else {
            view.widthAnchor.constraint(equalToConstant: 50).isActive = true
            view.backgroundColor = .red
        }
    
        stackView.addArrangedSubview(view)
    }
    

    }

  4. Result enter image description here

Jurkoic answered 20/4, 2018 at 10:14 Comment(0)
M
1

Yes you can, firstly you create main vertical stackview and set aligment center and distribution fill. Then you create second horizontal stackview in main stack and set alignment and distribition fill. Add the last elements you want to add Thats it.

First stackview: First stackview

Second stackview: second stackview

Monochloride answered 21/6, 2018 at 15:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.