IOS9 new Features--stacked view Uistackview

Source: Internet
Author: User

First, Introduction

With AutoLayout, more apps are starting to use auto-layout to build their own UI system, AutoLayout with storyboard and some third-party frameworks, which is handy for creating constraints, but for some dynamic, linear layout views , we need to manually add not only a lot of constraints, but also if we need to insert or remove some of the UI elements, we have to do a lot of changes to the constraints of the work, Uistackview just can solve such a problem.

Second, the first knowledge stackview on the storyboard

Uistackview is a controller Class view that manages a set of stacked views, a tiled, linear layout that does not overlap, and the layout direction is not interlaced, if you have done watchOS development, you will find that In fact StackView and watchOS in the group very similar.

For example, if we need a layout that looks like this, put a couple of consistent-sized patches in the middle of the screen, no matter where the screen is facing, where it doesn't change, and how many color blocks can be added and removed:

First, we pull a stackview into the Viewcontroller:

Set some properties as follows:

Axis is the orientation of the layout, horizontal and vertical, and a stackview can only select one layout mode.

Alignment is the alignment mode that selects its management view, where we select full.

Distribution is to set the arrangement of its management view, we choose equal width filled.

Spacing is to set the spacing between views, set to 10.

Then one thing to note is that StackView is used to layout its internal management view, and for itself, we need to add some constraints to constrain it in the middle of the screen.

We drag in any number of view, set different colors, we achieve the desired effect, and can arbitrarily delete and add the number of view in it, do not need to change the constraints.

Third, learn from the code Uistackview

Creating a Uistackview from code is also very simple, first, we first implement the above effect through code:

?
123456789101112131415161718  NSMutableArray * array = [[NSMutableArray alloc]init];    for(inti =0 ; i<5; i++) {        UIView * view = [[UIView alloc]init];        view.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];        [array addObject:view];    }    UIStackView * stackView = [[UIStackView alloc]initWithArrangedSubviews:array];    [self.view addSubview:stackView];    [stackView mas_makeConstraints:^(MASConstraintMaker *make) {        make.centerX.equalTo(self.view.mas_centerX);        make.centerY.equalTo(self.view.mas_centerY);        make.leading.equalTo(self.view.mas_leading).offset(20);        make.trailing.equalTo(self.view.mas_trailing).offset(-20);        make.size.height.equalTo(@100);    }];    stackView.axis = UILayoutConstraintAxisHorizontal;    stackView.distribution = UIStackViewDistributionFillEqually;    stackView.alignment = UIStackViewAlignmentFill;

As follows:

We have no problem with the layout, and can dynamically change the number of view, using the following method to add a view:

?
123     UIView * newView = [[UIView alloc]init];    newView.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];    [stackView addArrangedSubview:newView];

In contrast, we can remove a view using the following method:

?
12     UIView * view = [stackView arrangedSubviews].lastObject;    [stackView removeArrangedSubview:view];

Special Note: Addarrangedsubview and addsubview are very different, using the former is to try to add StackView layout management, the latter is simply added to the level of the attempt, do not accept stackview layout management.

Tip: Because StackView inherits from UIView, we can use the UIView layer animation when the layout changes, as follows:

?
12345         //在添加view的时候会有动画效果,移除的时候没有        [stackView addArrangedSubview:newView];        [UIView animateWithDuration:1 animations:^{            [stackView layoutIfNeeded];        }];
Four, to further understand the next Uistackview

Through the above introduction, we have a basic understanding of the use and characteristics of StackView, the following we will take a closer look at the use of its related properties and methods, so that we can more handy.

About the Add and remove of managed views:

?
12345678910 //初始化方法,通过数组传入被管理的视图- (instancetype)initWithArrangedSubviews:(NSArray<__kindof UIView *> *)views; //获取被管理的所有视图@property(nonatomic,readonly,copy) NSArray<__kindof UIView *> *arrangedSubviews;//添加一个视图进行管理- (void)addArrangedSubview:(UIView *)view;//移除一个被管理的视图- (void)removeArrangedSubview:(UIView *)view;//在指定位置插入一个被管理的视图- (void)insertArrangedSubview:(UIView *)view atIndex:(NSUInteger)stackIndex;

Related to StackView layout settings:

1. Layout mode:

?
1 @property(nonatomic) UILayoutConstraintAxis axis;

The above attribute is used to set the layout of the model, enumerated as follows:

?
1234567 //stackView只有两种布局模式 水平和竖直typedefNS_ENUM(NSInteger, UILayoutConstraintAxis) {    //水平布局    UILayoutConstraintAxisHorizontal = 0,    //竖直布局    UILayoutConstraintAxisVertical = 1};

2. Alignment Mode:

?
1 @property(nonatomic) UIStackViewAlignment alignment;

This property is used to set the control's mode to its enumeration as follows:

?
123456789101112131415161718 typedefNS_ENUM(NSInteger, UIStackViewAlignment) {   //水平布局时为高度充满,竖直布局时为宽度充满    UIStackViewAlignmentFill,    //前边对其    UIStackViewAlignmentLeading,    //顶部对其    UIStackViewAlignmentTop = UIStackViewAlignmentLeading,    //第一个控件文字的基线对其 水平布局有效    UIStackViewAlignmentFirstBaseline,     //中心对其    UIStackViewAlignmentCenter,    //后边对其    UIStackViewAlignmentTrailing,    //底部对其    UIStackViewAlignmentBottom = UIStackViewAlignmentTrailing,    //基线对其,水平布局有效    UIStackViewAlignmentLastBaseline, } NS_ENUM_AVAILABLE_IOS(9_0);

In the above example, we set the way for it to be full, so that we do not have to do too much control size constraints, if we are managed by the height or width of the control, we can set the center to it, so we also need to add a width or height constraint for each control, as follows:

?
12345678910111213141516171819202122     NSMutableArray * array = [[NSMutableArray alloc]init];    for(inti =0 ; i<5; i++) {        UIView * view = [[UIView alloc]init];        view.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];        floatheight = arc4random()%90+10;        [view mas_makeConstraints:^(MASConstraintMaker *make) {            make.height.equalTo([NSNumber numberWithFloat:height]);        }];        [array addObject:view];    }    stackView = [[UIStackView alloc]initWithArrangedSubviews:array];    [self.view addSubview:stackView];    [stackView mas_makeConstraints:^(MASConstraintMaker *make) {        make.centerX.equalTo(self.view.mas_centerX);        make.centerY.equalTo(self.view.mas_centerY);        make.leading.equalTo(self.view.mas_leading).offset(20);        make.trailing.equalTo(self.view.mas_trailing).offset(-20);        make.size.height.equalTo(@100);    }];    stackView.axis = UILayoutConstraintAxisHorizontal;    stackView.distribution = UIStackViewDistributionFillEqually;    stackView.alignment = UIStackViewAlignmentCenter;

The effect is as follows:

This way, we can also easily complete the uneven layout of the controls.

3. Arrangement method

?
1 @property(nonatomic) UIStackViewDistribution distribution;

An enumeration of the arrangement methods is as follows:

?
123456789101112 typedefNS_ENUM(NSInteger, UIStackViewDistribution) {    //充满,当只有一个控件时可以使用    UIStackViewDistributionFill = 0,    //平分充满,每个控件占据相同尺寸排列充满    UIStackViewDistributionFillEqually,    //会优先按照约束的尺寸进行排列,如果没有充满,会拉伸最后一个排列的控件充满    UIStackViewDistributionFillProportionally,    //等间距排列    UIStackViewDistributionEqualSpacing,    //中心距离相等    UIStackViewDistributionEqualCentering,} NS_ENUM_AVAILABLE_IOS(9_0);

Note that except that we do not need to constrain the size of the control view when we select the Fill property, others need to be constrained, for example, if we choose equal spacing, I change it to the following code:

?
123456        [view mas_makeconstraints:^ (masconstraintmaker *make)  {              make.height.equalto ([Nsnumber numberwithfloat:height]); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; make.width.equalto (@50); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP; stackview.distribution = uistackviewdistributionequalspacing;

The effect is as follows:

4. Other

?
123456 //设置最小间距@property(nonatomic) CGFloat spacing;//设置布局时是否参照基线@property(nonatomic,getter=isBaselineRelativeArrangement) BOOLbaselineRelativeArrangement;//设置布局时是否以控件的LayoutMargins为标准,默认为NO,是以控件的bounds为标准@property(nonatomic,getter=isLayoutMarginsRelativeArrangement) BOOLlayoutMarginsRelativeArrangement;
V. Nesting of Uistackview

A stackview does not allow us to have horizontal and vertical cross-layouts, but we can implement complex layout effects in a nested way, such as we implement a similar movie table label, which can be nested in a horizontal layout of the StackView with a vertical layout of StackView:

It is very easy to achieve the following effects:

See, through StackView, we didn't add too many constraints, making it easier to lay out. If you often use storyboard for development, there is a small trick to easily integrate two controls into a StackView, command, select two controls, then click on the lower right corner of the label, the system will automatically help us generate a stackview, It's cool to integrate the two selected controls in it!

Original link: iOS9 new feature--stacked view Uistackview

IOS9 new Features--stacked view Uistackview

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.