UIStackView的运用
文章目录
引入
在仿写ZARA的过程之中,我看到软件之中是有大量的按钮排列在一起的,如果自己一个一个手动将按钮给添加到主视图之中,布局就会感觉十分麻烦,为了方便操作,于是我便学习了UIStackView的相关用法来简化布局的繁琐。
UIStackView的作用
UIStackView又可以被称作堆栈视图,是一种存储视图的容器,用于简化和管理其子视图的布局和排列。
它提供了一个高效的接口用于平铺一行或一列的视图组合。对于嵌入到 StackView 的视图,我们不用再添加自动布局的约束了。UIStackView会管理这些子视图的布局,并帮我们自动布局约束。也就是说,这些子视图能够适应不同的屏幕尺寸。也就是说我们只需要去管理UIStackView本身的布局,而其中的子视图的布局可以由调控UIStackView之中的属性来进行操作。
UIStackView能对布局的代码进行化简,减少了手动添加和管理约束的工作量。而且作为一个容器,删除或者添加某一个视图时,十分便利,可以使用相关方法进行动态的操作,而且布局还会相应的进行自动布局。
另外,UIStackView 支持嵌套,我们可以将一个 Stack View 嵌套到另一个 Stack View 中,从而实现更为复杂的用户界面。(但我还未使用过)
与其他继承于``UIView`的视图不同,UIStackView 它本身不能自我渲染,比如他的 backgroundColor 是无效的,所以它注定要和 UIView 相辅相成的进行工作。它能够帮助 UIView 来处理 子View 的位置和大小等布局问题。
UIStackView的属性
compression resistance 和 hugging
compression resistance(抗压缩性)和 hugging(抗拉伸性)是 UIStackView 中的两个属性,用于控制子视图在布局过程中的压缩和拉伸行为。通常情况下,较高的值表示子视图更不容易被压缩(compression resistance)或拉伸(hugging)。
我们一般使用[view setContentHuggingPriority:(UILayoutPriority) forAxis:(UILayoutConstraintAxis)]来对其进行设置
UILayoutPriority为float类型的浮点数,具体枚举类型如下:
typedef float UILayoutPriority NS_TYPED_EXTENSIBLE_ENUM;
static const UILayoutPriority UILayoutPriorityRequired API_AVAILABLE(ios(6.0)) = 1000; // A required constraint. Do not exceed this.
static const UILayoutPriority UILayoutPriorityDefaultHigh API_AVAILABLE(ios(6.0)) = 750; // This is the priority level with which a button resists compressing its content.
static const UILayoutPriority UILayoutPriorityDragThatCanResizeScene API_AVAILABLE(macCatalyst(13.0)) = 510; // This is the appropriate priority level for a drag that may end up resizing the window's scene.
static const UILayoutPriority UILayoutPrioritySceneSizeStayPut API_AVAILABLE(macCatalyst(13.0)) = 500; // This is the priority level at which the window's scene prefers to stay the same size. It's generally not appropriate to make a constraint at exactly this priority. You want to be higher or lower.
static const UILayoutPriority UILayoutPriorityDragThatCannotResizeScene API_AVAILABLE(macCatalyst(

最低0.47元/天 解锁文章
1655

被折叠的 条评论
为什么被折叠?



