UIStackView

因为之前项目支持最低版本是iOS8,所以没考虑使用stackView,有类似的场景也都使用tableView或collectionView解决了,现在项目最低支持iOS9+,再加上最近要封装一个组件,所以有些场景使用这个stackView更便捷一些。
这个类是干嘛的?
别着急,往下看,看完了还不明白是干嘛的,电话联系!!!

目前UIStackView只支持在大于等于iOS9+的系统上使用,如果想要在iOS9以下的系统上使用,sunnyxx团队的新作FDStackView了解一下
首先,我们先看一下这个类的初始化API

@interface UIStackView : UIView

- (instancetype)initWithFrame:(CGRect)frame NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithCoder:(NSCoder *)coder NS_DESIGNATED_INITIALIZER;

/* UIStackView enforces that all views in the arrangedSubviews list
 must be subviews of the UIStackView.
    Thus, when a view is added to the arrangedSubviews, UIStackView
 adds it as a subview if it isn't already. And when a view in a
 UIStackView's arrangedSubviews list receives -removeFromSuperview
 it is also removed from the arrangedSubviews.
 
 Please note that this is a convenience initializer and cannot be overridden in Swift.
 */
- (instancetype)initWithArrangedSubviews:(NSArray<__kindof UIView *> *)views; // Adds views as subviews of the receiver.

乍一看 没什么特别的,不要着急,接着往下看

/* Add a view to the end of the arrangedSubviews list.
 Maintains the rule that the arrangedSubviews list is a subset of the
 subviews list by adding the view as a subview of the receiver if
 necessary.
    Does not affect the subview ordering if view is already a subview 
 of the receiver.
 */
- (void)addArrangedSubview:(UIView *)view;

/* Removes a subview from the list of arranged subviews without removing it as
 a subview of the receiver.
    To remove the view as a subview, send it -removeFromSuperview as usual;
 the relevant UIStackView will remove it from its arrangedSubviews list
 automatically.
 */
- (void)removeArrangedSubview:(UIView *)view;
/*
 Adds the view as a subview of the container if it isn't already.
    Updates the stack index (but not the subview index) of the
 arranged subview if it's already in the arrangedSubviews list.
 */
- (void)insertArrangedSubview:(UIView *)view atIndex:(NSUInteger)stackIndex;

是不是有点熟悉了?好像类似的API在哪见过,可变容器的API跟这个很像!
其实我们可以把UIStackView当成是一个容器视图,他继承于UIView,当然他父级API他也都支持可用,完全可以当成UIView来使用,不对,因为它不做渲染,所以你不能够设置它的背景色和重构它的Draw方法,为什么不做渲染?个人猜测是因为苹果官方推出这个stackView的目的是用于简化布局,并不是让你针对stackView本身来进行视图渲染操作,你可以把stackView当成一个排兵布阵的演练场,当然这不是我们这篇的主题。

*注意这里如果同时调用addArrangedSubview和insertArrangedSubview:atIndex:类似这种

[self.stackView insertArrangedSubview:view atIndex:0];
[self.stackView addArrangedSubview:view];

那么他只显示后执行的函数效果,当然显示的顺序也就不一样!

还有一点需要注意的是,假如你调用removeArrangedSubview :这里的remove并不是视图从stackView上移除掉,其实视图还是存在的,为了避免出问题,在你的子view确定不需要显示了的时候可以removeFromSuperview或hidden掉!

UIView *tempView = self.stackView.arrangedSubviews.lastObject;
[self.stackView removeArrangedSubview:tempView];
[tempView removeFromSuperview];

注意千万不要这样写

[self.stackView removeArrangedSubview:self.stackView.arrangedSubviews.lastObject];
[tempView removeFromSuperview];

这样是remove不掉的。

UIStackView 类提供了一个高效的接口用于平铺一行或一列的视图组合,UIStackView提供了高效的单行单列自动布局的手段,一般情况下,我们不需要对stackView.subviews做任何约束,增删插入视图的操作只要调用上边的API即可实现,然后再通过对stackView的axis, distribution, alignment, spacing属性进行修改;

另外,stackview的一个特点是,当把其中的一个子view去掉后,会重新布局,省去了以前大把大把的代码。那么这个所谓的去掉是什么操作呢?一般来说,是设置子view的hidden = true,并且调用 stackview 的函数,removeArrangedSubview。在当前ios版本,如果仅仅设置hidden属性,在有些时候,可能无法对剩下的子view进行自动布局。当需要重新显示的时候,设置hidden属性,并调用insertArrangedSubview: atIndex:方法就可以了。

接下来我们来看看几个抽象属性的设置

/* A stack with a horizontal axis is a row of arrangedSubviews,
and a stack with a vertical axis is a column of arrangedSubviews.
 */
@property(nonatomic) UILayoutConstraintAxis axis;

/* The layout of the arrangedSubviews along the axis
 */
@property(nonatomic) UIStackViewDistribution distribution;

/* The layout of the arrangedSubviews transverse to the axis;
 e.g., leading/trailing edges in a vertical stack
 */
@property(nonatomic) UIStackViewAlignment alignment;

/* Spacing between adjacent edges of arrangedSubviews.
 Used as a strict spacing for the Fill distributions, and
 as a minimum spacing for the EqualCentering and EqualSpacing
 distributions. Use negative values to allow overlap.
 
 On iOS 11.0 or later, use UIStackViewSpacingUseSystem (Swift: UIStackView.spacingUseSystem) 
 to get a system standard spacing value. Setting spacing to UIStackViewSpacingUseDefault 
 (Swift: UIStackView.spacingUseDefault) will result in a spacing of 0.
 
 System spacing between views depends on the views involved, and may vary across the 
 stack view.
 
 In vertical stack views with baselineRelativeArrangement == YES, the spacing between 
 text-containing views (such as UILabels) will depend on the fonts involved.
 */
@property(nonatomic) CGFloat spacing;

axis

枚举了一个布局方向

//
// UIView Constraint-based Layout Support
//

typedef NS_ENUM(NSInteger, UILayoutConstraintAxis) {
    UILayoutConstraintAxisHorizontal = 0,
    UILayoutConstraintAxisVertical = 1
};

UILayoutConstraintAxisHorizontal水平布局
UILayoutConstraintAxisVertical 垂直布局
这里没啥好说的,基本都知道

distribution

这个稍微抽象一些,你可以理解成视图分布的样式规则

/* Distribution—the layout along the stacking axis.
 
 All UIStackViewDistribution enum values fit first and last arranged subviews tightly to the container,
 and except for UIStackViewDistributionFillEqually, fit all items to intrinsicContentSize when possible.
 */
typedef NS_ENUM(NSInteger, UIStackViewDistribution) {
    
    /* When items do not fit (overflow) or fill (underflow) the space available
     adjustments occur according to compressionResistance or hugging
     priorities of items, or when that is ambiguous, according to arrangement
     order.
     */
    UIStackViewDistributionFill = 0,
    
    /* Items are all the same size.
     When space allows, this will be the size of the item with the largest
     intrinsicContentSize (along the axis of the stack).
     Overflow or underflow adjustments are distributed equally among the items.
     */
    UIStackViewDistributionFillEqually,
    
    /* Overflow or underflow adjustments are distributed among the items proportional
     to their intrinsicContentSizes.
     */
    UIStackViewDistributionFillProportionally,
    
    /* Additional underflow spacing is divided equally in the spaces between the items.
     Overflow squeezing is controlled by compressionResistance priorities followed by
     arrangement order.
     */
    UIStackViewDistributionEqualSpacing,
    
    /* Equal center-to-center spacing of the items is maintained as much
     as possible while still maintaining a minimum edge-to-edge spacing within the
     allowed area.
        Additional underflow spacing is divided equally in the spacing. Overflow 
     squeezing is distributed first according to compressionResistance priorities 
     of items, then according to subview order while maintaining the configured 
     (edge-to-edge) spacing as a minimum.
     */
    UIStackViewDistributionEqualCentering,
} NS_ENUM_AVAILABLE_IOS(9_0);

UIStackViewDistributionFill 铺满
UIStackViewDistributionFillEqually等宽铺满
UIStackViewDistributionFillProportionally 等比例铺满
UIStackViewDistributionEqualSpacing 等距离放置
UIStackViewDistributionEqualCentering 各个试图的中心距离保持一致,不够放置则压缩后面的试图距离

alignment

对齐方式

/* Alignment—the layout transverse to the stacking axis.
 */
typedef NS_ENUM(NSInteger, UIStackViewAlignment) {
    /* Align the leading and trailing edges of vertically stacked items
     or the top and bottom edges of horizontally stacked items tightly to the container.
     */
    UIStackViewAlignmentFill,
    
    /* Align the leading edges of vertically stacked items
     or the top edges of horizontally stacked items tightly to the relevant edge
     of the container
     */
    UIStackViewAlignmentLeading,
    UIStackViewAlignmentTop = UIStackViewAlignmentLeading,
    UIStackViewAlignmentFirstBaseline, // Valid for horizontal axis only
    
    /* Center the items in a vertical stack horizontally
     or the items in a horizontal stack vertically
     */
    UIStackViewAlignmentCenter,
    
    /* Align the trailing edges of vertically stacked items
     or the bottom edges of horizontally stacked items tightly to the relevant
     edge of the container
     */
    UIStackViewAlignmentTrailing,
    UIStackViewAlignmentBottom = UIStackViewAlignmentTrailing,
    UIStackViewAlignmentLastBaseline, // Valid for horizontal axis only
} NS_ENUM_AVAILABLE_IOS(9_0);

UIStackViewAlignmentFill 垂直方向上铺满
UIStackViewAlignmentTopUIStackViewAlignmentLeading 沿顶端对齐
UIStackViewAlignmentCenter 沿中心线对齐
UIStackViewAlignmentBottomUIStackViewAlignmentTrailing 沿底部对齐
UIStackViewAlignmentFirstBaseline 按照第一个子视图的文字的第一行对齐,同时保证高度最大的子视图底部对齐(只在axis为水平方向有效)
UIStackViewAlignmentLastBaseline 按照最后一个子视图的文字的最后一行对齐,同时保证高度最大的子视图顶部对齐(只在axis为水平方向有效)

spacing

属性决定了其管理的视图间的最小间隙,为什么这里说是最小间距,因为stackView根据你设置的分布规则来布局的时候发现放不下所有的视图,那么就会压缩约束优先级较低的,如果优先级相同,则会按顺序来压缩.
举个栗子:假设你给stackView的约束宽度为100,这时候你添加了俩子view,其宽度都是50,然后间距是10,这时候明显按照布局是放不下的,那么stackView会根据俩view的约束优先级来约束,如果优先级相同,则按照索引来压缩,再假如第二个view先一步addArrangedSubview 那么就会压缩第一个view,反之亦然。

baselineRelativeArrangement属性决定了其视图间的垂直间隙是否根据基线测量得到,选中 Baseline Relative 将根据subview的基线调整垂直间距
layoutMarginsRelativeArrangement属性决定了 stack 视图平铺其管理的视图时是否要参照它的布局边距,选中 Layout Margins Relative 将相对于标准边界空白来调整subview位置

今天先写到这 要下班了 需要demo的话 等我写一个上传到github
你们要的demo

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,490评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,581评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,830评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,957评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,974评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,754评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,464评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,847评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,995评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,137评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,819评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,482评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,023评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,149评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,409评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,086评论 2 355

推荐阅读更多精彩内容

  • 前言 首先,我们通过下面这张图片引出今天的主角 大家看到了什么,是爱吗?不,这不是爱,不是爱,是满满的‘愁绪’?😂...
    一念之见阅读 2,201评论 0 2
  • 这是一篇挺老的文章,主要就是介绍在iOS9时推出的控件UIStackView。我发现网上的资料并不算多,而AppC...
    Liberalism阅读 11,096评论 2 26
  • 版本记录 前言 iOS中的视图加载可以有两种方式,一种是通过xib加载,另外一种就是通过纯代码加载。它们各有优点和...
    刀客传奇阅读 5,357评论 0 7
  • 概述 UIStackView是iOS9中新增的API,类似于Android中的线性布局。UIStackView提供...
    随梦而飞飞阅读 3,589评论 0 12
  • UIStackView to resize/layout 自适应、适配、布局这几个关键词一直伴随着iOS开发,从以...
    萌新小透明阅读 2,109评论 1 1