Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIStackview align left

I'm trying to align the items in UIStackview horizontally to the left.

Is there anyway to do this programmatically? I tried to do this via storyboard but was not successful. For some reason, the items in the UIStackView centers itself.

like image 430
Yong Jia Pao Avatar asked Dec 28 '16 19:12

Yong Jia Pao


People also ask

What is Stackview alignment?

A layout where the stack view aligns the center of its arranged views with its center along its axis. case leading. A layout for vertical stacks where the stack view aligns the leading edge of its arranged views along its leading edge.

What is Uistackview?

A streamlined interface for laying out a collection of views in either a column or a row.


2 Answers

If you use StackView setting axis property to "Horizontal", I think you can't align it to the left.

But there is a way to make it left visually.

  1. set StackView leading constraint with "equal" relationship
  2. set StackView trailing constraint with "greater than or equal"

like this

stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(greaterThanOrEqualTo: view.trailingAnchor).isActive = true
like image 198
shtnkgm Avatar answered Sep 18 '22 03:09

shtnkgm


Try Adding One Space View in Your Stack View , Like this

 // To Make Our Buttons aligned to left We have added one spacer view
    UIButton *spacerButton = [[UIButton alloc] init];
    [spacerButton setContentHuggingPriority:UILayoutPriorityFittingSizeLevel forAxis:UILayoutConstraintAxisHorizontal];
    [spacerButton setContentCompressionResistancePriority:UILayoutPriorityFittingSizeLevel forAxis:UILayoutConstraintAxisHorizontal];
    [self.buttonsStackView addArrangedSubview:spacerButton];

And Make

self.buttonsStackView.distribution = UIStackViewDistributionFill;
like image 45
Ankit Maurya Avatar answered Sep 22 '22 03:09

Ankit Maurya