Uistackview Stacked View Usage Tutorial in IOS app development _ios

Source: Internet
Author: User

First, the introduction
with AutoLayout, more apps are starting to use automatic layout to build their own UI systems, AutoLayout with storyboard and a few third-party frameworks that are already 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 modification constraints of the work, Uistackview just can solve this problem.


second, on the storyboard of the first to recognize StackView
Uistackview is a view of the Controller class that manages a set of stacked views, the so-called stacked view of a tiled linear layout, not overlapping, layout direction can not be staggered, if you have done watchOS development, you will find that In fact, StackView and watchOS group are very similar.
For example, if we need a layout with the following effect, place several color blocks in the middle of the screen, regardless of the screen orientation, the position will not change, and the number of color blocks can be added and removed:

First, we pull a stackview in the Viewcontroller:

Set some of the properties as follows:

Axis is the orientation of the layout, in both horizontal and vertical ways, and one stackview can only choose one layout mode.
Alignment is the alignment pattern that selects its management view, which we choose to fill here.
Distribution is the way to set its management view, and we choose to fill it with equal width.
Spacing is to set the spacing between views, set to 10.
Then one thing to note is that StackView is used to lay out its internal management view, and for itself, we need to add some constraints and constrain it to the middle of the screen.
We drag in any number of view, set a different color, we achieve the desired effect, and can dynamically delete and add the view quantity, do not need to change the constraints.


third, learn from the code Uistackview
Creating a Uistackview through code is also very simple, first of all, we first achieve the above effect through code:
Nsmutablearray * array = [[Nsmutablearray alloc]init];
for (int i =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;
The effect chart is as follows:

We have no problem with the layout, and can change the number of view dynamically, using the following method to add a view:
    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];
与之相对,我们可以使用下面的方法移除一个view:
    UIView * view = [stackView arrangedSubviews].lastObject;
    [stackView removeArrangedSubview:view];
Special Note: Addarrangedsubview and addsubview are very different, using the former is the layout management that will attempt to add into the StackView, the latter is simply added to the level of the attempt and does not accept StackView layout management.
Tip: Because StackView inherits from UIView, when the layout changes, we can use the UIView layer of animation, as follows:
        //在添加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 of stackview and characteristics, and then we have to carefully introduce its related properties and methods of use, so that we can be more handy.
For additions and removal of managed views:
//初始化方法,通过数组传入被管理的视图
- (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:
@property(nonatomic) UILayoutConstraintAxis axis;
The above property is used to set the model of the layout, as follows:
//stackView只有两种布局模式 水平和竖直
typedef NS_ENUM(NSInteger, UILayoutConstraintAxis) {
    //水平布局
    UILayoutConstraintAxisHorizontal = 0,
    //竖直布局
    UILayoutConstraintAxisVertical = 1
};
2. Alignment Mode:
@property(nonatomic) UIStackViewAlignment alignment;
This property is used to set the control's mode to its schema, which is enumerated as follows:
typedef NS_ENUM(NSInteger, UIStackViewAlignment) {
   //水平布局时为高度充满,竖直布局时为宽度充满
    UIStackViewAlignmentFill,
    //前边对其
    UIStackViewAlignmentLeading,
    //顶部对其
    UIStackViewAlignmentTop = UIStackViewAlignmentLeading,
    //第一个控件文字的基线对其 水平布局有效
    UIStackViewAlignmentFirstBaseline,
    //中心对其
    UIStackViewAlignmentCenter,
    //后边对其
    UIStackViewAlignmentTrailing,
    //底部对其
    UIStackViewAlignmentBottom = UIStackViewAlignmentTrailing,
    //基线对其,水平布局有效
    UIStackViewAlignmentLastBaseline,
} NS_ENUM_AVAILABLE_IOS(9_0);
In the example above, we set the way for it to be filled, in this case, we do not need to do too much control size constraints, if we are managed by the control height or width of different, we can set the center to it, so we also need to add a width or height for each control constraints, as follows:
Nsmutablearray * array = [[Nsmutablearray alloc]init];
for (int i =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];
float height = 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:

In this way, the uneven layout of the control can also be easily done.
3. Arrange the way
@property(nonatomic) UIStackViewDistribution distribution;
The permutations are enumerated as follows:
typedef NS_ENUM(NSInteger, UIStackViewDistribution) {
    //充满,当只有一个控件时可以使用
    UIStackViewDistributionFill = 0,
    //平分充满,每个控件占据相同尺寸排列充满
    UIStackViewDistributionFillEqually,
    //会优先按照约束的尺寸进行排列,如果没有充满,会拉伸最后一个排列的控件充满
    UIStackViewDistributionFillProportionally,
    //等间距排列
    UIStackViewDistributionEqualSpacing,
    //中心距离相等
    UIStackViewDistributionEqualCentering,
} NS_ENUM_AVAILABLE_IOS(9_0);
Note that in addition to the size of the control view that we select without constraining the Fill property, other constraints are required, for example, if we choose spacing, I will change to the following code:
     [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo([NSNumber numberWithFloat:height]);
            make.width.equalTo(@50);
           
        }];
     stackView.distribution = UIStackViewDistributionEqualSpacing;
The effect is as follows:

4. Other
//设置最小间距
@property(nonatomic) CGFloat spacing;
//设置布局时是否参照基线
@property(nonatomic,getter=isBaselineRelativeArrangement) BOOL baselineRelativeArrangement;
//设置布局时是否以控件的LayoutMargins为标准,默认为NO,是以控件的bounds为标准
@property(nonatomic,getter=isLayoutMarginsRelativeArrangement) BOOL layoutMarginsRelativeArrangement;

Five, Uistackview nesting
a stackview does not allow us to make horizontal and vertical cross layouts, but we can implement complex layout effects in nested ways, such as we implement a label like a movie table, You can use a stackview that is nested vertically in the horizontal layout of the StackView:

It is very easy to achieve the following effects:

See, through the StackView, we did not add too many constraints, so that we are more relaxed layout. If you often use storyboard for development, there is a small trick to easily consolidate two controls into a stackview, hold command, select two controls, and then click on the lower right corner of the following icon, the system will automatically help us generate a stackview, It's cool to integrate the two selected controls.

Vi. Summary
Uistackview, although small and flexible, but to the more exquisite effect, ultimately rely on Uicollectionview, see Weibo some people say that this class may be born from Apple Watch, very likely, on such a small screen, and drag a variety of constraints to align and adjust the position is really annoying to death. It's not very useful to get a pass. On the push, see a lot of developers are excited about this class:
The view from Twitter:

Because Uistackview can be nested, to achieve the above mitosis is very convenient, if the use of Uicollectionview is absolutely fatal. And one developer said that after all these years, there was a uitableview that could not be slid. Because I have a shallow experience, I do not know how these requirements are generated, or my brain hole is too small, do not know this can facilitate the implementation of what effect.
Overall, the Uistackview implementation of the alignment requirements of the view layout is very simple, and the use of Uicollectionview and UITableView to achieve a more cumbersome, but also real-time in the IB to preview the effect. Finally a bit inconvenient is, because Uistackview is using the UIView class Intrinsiccontentsize properties to calculate the layout, the different aspect ratio and resolution of the picture alignment and position adjustment is not very strong, that is, the use of UIView To carry out encapsulation to a layer is also basically ineffective, in addition to the original image scaling, for the time being not found a good solution.

Related Article

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.