【OC】巧用UIStackView简化布局

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(13.0)) = 490; // This is the priority level at which a split view divider, say, is dragged.  It won't resize the window's scene.
static const UILayoutPriority UILayoutPriorityDefaultLow API_AVAILABLE(ios(6.0)) = 250; // This is the priority level at which a button hugs its contents horizontally.
static const UILayoutPriority UILayoutPriorityFittingSizeLevel API_AVAILABLE(ios(6.0)) = 50; 

UILayoutConstraintAxis为float类型的浮点数,具体枚举类型如下:

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

axis

该属性规定了UIStackView的布局方向

  • Vertical: 垂直
  • Horizontal: 水平(默认值)

alignment

子视图的对齐方式

.fill: (默认) 尽可能铺满。

.leading: 当 axis 是 vertical 的时候,按 leading 方向对齐 等价于: 当 axis 是 horizontal 的时候,按 top 方向对齐。

.top: 当 axis 是 horizontal 的时候,按 top 方向对齐 等价于: 当 axis 是 vertical 的时候,按 leading 方向对齐。

.trailing: 当 axis 是 vertical 的时候,按 trailing 方向对齐 等价于: 当 axis 是 horizontal 的时候,按 bottom 方向对齐。

bottom: 当 axis 是 horizontal 的时候,按 bottom 方向对齐 等价于: 当 axis 是 vertical 的时候,按 trailing 方向对齐。

.center:居中对齐。

Distribution

定义沿堆栈视图轴排列视图的大小和位置的布局。

  • fill: (默认值) 根据compression resistance和hugging两个 priority 布局
  • fillEqually: 均匀分布
  • fillProportionally: 按比例分布
  • equalSpacing: 等间距布局,内容大小调整
  • equalCentering: 等中间线间距布局,元素间距不小于 spacing 定义的值, 如果放不下,根据compression resistance压缩。
typedef NS_ENUM(NSInteger, UIStackViewDistribution) 
    UIStackViewDistributionFill = 0
    UIStackViewDistributionFillEqually,
    UIStackViewDistributionFillProportionally,
    UIStackViewDistributionEqualSpacing,
    UIStackViewDistributionEqualCentering,
} API_AVAILABLE(ios(9.0));

spacing

spacing 属性确定子视图之间的间距。它是一个浮点数,表示子视图之间的固定间距。默认值为0。可以根据需要调整间距大小,以实现子视图之间的空白区域。

UIStackView的方法

  • init(frame: CGRect):创建一个 UIStackView
  • init(arrangedSubviews views: [UIView]):同样是创建一个 UIStackView,但我们可以将子视图传入。views 数组里的顺序即为子视图显示的顺序。
  • addArrangedSubview(view: UIView):添加一个子视图
  • removeArrangedSubview(view: UIView):删除一个子视图
  • insertArrangedSubview(view: UIView, at stackIndex: Int):在指定位置插入一个子视图

注:如果一个元素没有被 addSubview,调用 arrangedSubviews 会自动 addSubview。当一个元素被 removeFromSuperview ,则 arrangedSubviews也会同步移除当一个元素被 removeArrangedSubview, 不会触发 removeFromSuperview,它依然在视图结构中。

UIStackView的示例

在进行仿写的过程之中,我使用UIStackView来存储按钮,相关代码如下:

- (void)setupTopBar {
    self.topBarView = [[UIView alloc] initWithFrame:CGRectZero];
    self.topBarView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.topBarView];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    titleLabel.text = @"ZARA";
    titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:60];
    titleLabel.textAlignment = NSTextAlignmentLeft;
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.topBarView addSubview:titleLabel];
    
    // 创建分类标签
    UIStackView *categoryStackView = [[UIStackView alloc] initWithFrame:CGRectZero];
    categoryStackView.axis = UILayoutConstraintAxisHorizontal;
    categoryStackView.alignment = UIStackViewAlignmentCenter;
    categoryStackView.distribution = UIStackViewDistributionFillEqually;
    categoryStackView.translatesAutoresizingMaskIntoConstraints = NO;
    for (int i = 0; i < self.categories.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        [button setTitle:self.categories[i] forState:UIControlStateNormal];
        button.tag = i;
        [button addTarget:self action:@selector(categoryButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
        button.titleLabel.font = [UIFont systemFontOfSize:16];
        button.tintColor = [UIColor blackColor];
        [categoryStackView addArrangedSubview:button];
    }
    [self.topBarView addSubview:categoryStackView];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.topBarView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor constant:-30],
        [self.topBarView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.topBarView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.topBarView.heightAnchor constraintEqualToConstant:150],
        
        [titleLabel.topAnchor constraintEqualToAnchor:self.topBarView.topAnchor],
        [titleLabel.leadingAnchor constraintEqualToAnchor:self.topBarView.leadingAnchor],
        [titleLabel.trailingAnchor constraintEqualToAnchor:self.topBarView.trailingAnchor],
        [titleLabel.heightAnchor constraintEqualToConstant:100],
        
        [categoryStackView.topAnchor constraintEqualToAnchor:titleLabel.bottomAnchor],
        [categoryStackView.leadingAnchor constraintEqualToAnchor:self.topBarView.leadingAnchor],
        [categoryStackView.trailingAnchor constraintEqualToAnchor:self.topBarView.trailingAnchor]
    ]];
}

以上代码实现了,五个相关按钮的布局,按钮在点击之后会切换无限视图的图片种类为对应按钮名称。

请添加图片描述

相关推荐

  1. count与count()

    2024-07-12 13:58:03       28 阅读
  2. lambda表达式构建各种“树”

    2024-07-12 13:58:03       34 阅读
  3. ChatGPT之道:写作技巧

    2024-07-12 13:58:03       29 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 13:58:03       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 13:58:03       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 13:58:03       45 阅读
  4. Python语言-面向对象

    2024-07-12 13:58:03       55 阅读

热门阅读

  1. 数据结构第21节 归并排序以及优化方案

    2024-07-12 13:58:03       19 阅读
  2. 手撕红黑树

    2024-07-12 13:58:03       18 阅读
  3. python程序打包.exe文件

    2024-07-12 13:58:03       18 阅读
  4. vue3+antd+g2plot快速入门

    2024-07-12 13:58:03       22 阅读
  5. 硬件产品经理:电子产品加工成本

    2024-07-12 13:58:03       19 阅读
  6. 1.人工智能核心概念

    2024-07-12 13:58:03       19 阅读
  7. C++语法提高A-字节对齐

    2024-07-12 13:58:03       19 阅读
  8. Vue 3中 watch 和 watchEffect的区别?

    2024-07-12 13:58:03       19 阅读