[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;
效果图如下:


我们的布局没有问题,并且可以动态的改变其中view的个数,使用如下方法添加一个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];
特别注意:addArrangedSubview和addSubview有很大的区别,使用前者是将试图添加进StackView的布局管理,后者只是简单的加在试图的层级上,并不接受StackView的布局管理。
技巧:因为StackView继承于UIView,因此在布局改变的时候,我们可以使用UIView层的动画,如下:
//在添加view的时候会有动画效果,移除的时候没有
[stackView addArrangedSubview:newView];
[UIView animateWithDuration:1 animations:^{
[stackView layoutIfNeeded];
}];
四、再来深入理解下UIStackView
通过上面的介绍,我们已经基本了解了StackView的使用和特点,下面我们再来仔细介绍一下与其相关的属性和方法的使用,使我们能够更加得心应手。










