iOS 9 adds UIStackView official documentation translation

iOS 9 adds UIStackView official documentation translation

[[138768]]

1. Inheritance, Compliance, Affiliation Framework and Available Platforms

The UIStackView class provides an efficient interface for laying out a collection of views in a row or column. Stack views enable you to take advantage of the power of Auto Layout to create user interfaces that dynamically adjust to changes in device orientation, screen size, and any other available context. The Stack view manages the layout of all the views in its arrangedSubviews property. The views are arranged along the axis of the Stack view according to the order in which they appear in the arrangedSubviews array. The exact layout variables are determined by the Stack view’s axis, distribution, alignment, spacing, and other properties.

To use the stack view, open a Storyboard you want to edit, drag a Horizontal Stack View or a Vertical Stack View from the Object Library, and place it where you want it. Next, drag controls or views into the stack. If necessary, you can continue to add views or controls to the specified stack. Interface Builder will automatically adjust the size based on the contents of the stack. You can also adjust the appearance of the stack contents by modifying the properties of the Stack view in the Properties Inspector.

Note: You are responsible for specifying the position and (optionally) the size of the stack view. The stack view then manages the layout and size of its content.

2. Stack View and Automatic Layout

The stack view uses Auto Layout to position and control the size of the views it manages. The stack view stitches the first and last managed views together along its axis so that their borders are flush. For a horizontal stack view, this means that the left border of the first managed view is flush with the left border of the stack, and the right border of the last managed view is flush with the right border of the stack. For a vertical stack, the top and bottom borders are flush with each other. If you set the stack view’s layoutMarginsRelativeArrangement property to YES, the stack view uses relative margins to align with its content instead of its borders.

For distribution methods other than UIStackViewDistributionFillEqually, the stack view uses the intrinsicContentSize property of the managed view to calculate the view size along the stack axis. UIStackViewDistributionFillEqually will adjust all managed views to have the same size along the stack axis to fill the stack view. If possible, the stack view will stretch all managed views to match their longest original size along the stack axis (Translator's note: stretch the view according to the stack axis length while ensuring the aspect ratio).

For alignments other than UIStackViewAlignmentFill, the stack view uses the intrinsicContentSize property of the views it manages to calculate the size of the view perpendicular to the stack axis. UIStackViewAlignmentFill rescales all of its managed views so that they fill the stack view's space perpendicular to its axis. If possible, the stack view stretches all of its managed views to match their maximum intrinsic size perpendicular to the stack axis.

3. Positioning and resizing the Stack view

While the stack view allows you to lay out its content without using Auto Layout directly, you will still need to use Auto Layout to position the stack view. Typically, this means piecing together at least two stacks with adjacent borders to define its position. Without additional constraints, the system calculates a size for the stack view to fit its content:

Along the stack view axis, its adaptive size is equal to the sum of the size of the views it manages and the spacing;

Perpendicular to the stack view axis, its adaptation size is equal to the size of the largest view in the views it manages;

If the stack view’s layoutMarginsRelativeArrangement property is set to YES , the stack view’s adaptive size includes the margin space.

You can provide additional constraints to specify the stack view’s height, width, or both. In these cases, the stack view adjusts the layout and size of the views it manages to fill the specified area. The exact layout variables are obtained from the stack view’s properties. You can see the UIStackViewDistribution and UIStackViewAlignment enumerations for a complete description of how the stack view handles situations where there is too much or too little space for its content.

You can also position the stack view based on its first or last baseline instead of using the top, bottom, or center Y value. Similar to the stack view's adaptive sizing, these baselines are calculated based on the stack view's content.

A horizontal stack view returns its original view when the viewForFirstBaselineLayout method or viewForLastBaselineLayout method is called. If the original view is also a stack view, then what is returned will be the result of calling the viewForFirstBaselineLayout method or viewForLastBaselineLayout method on the nested stack view.

A vertical stack view returns the first view it manages when the viewForFirstBaselineLayout method is called, and returns the last view it manages when the viewForLastBaselineLayout method is called. If one of the two views is also a stack view, then what is returned will be the result of calling the viewForFirstBaselineLayout method or viewForLastBaselineLayout method on the nested stack view.

Note: Baseline alignment only works for views whose height matches the height of their native content. If the view is stretched or compressed, the baseline will appear in the wrong place.

4. General Stack View Layout

There are some common methods used with stack views. This list is meant to highlight some useful examples that show the flexibility of the stack view. This is not a complete list at this time.

Just define the position. You can define the position of a stack view by pinning two borders adjacent to its superview. Here, the size of the stack view will expand freely in two dimensions based on the views it manages. This is particularly useful when you want the content of the stack view to show its native content size, and you want to manage other user interface elements associated with the stack view.

For example, in Figure 1, the stack view's left and top edges are both fixed relative to its superview. The labels will be aligned based on the space between them with 8 points as the ultimate baseline. This is effective for the stack view content to be left-aligned relative to itself.

Figure 1. Defining the location

Define the size along the stack view’s axis. Here, you pin two edges along the stack view’s axis relative to its superview, defining the stack view’s size along its axis. You’ll need to pin one of the other edges to define the stack view’s position. The stack view will change size and position along its axis to fill the defined space; however, unpinned edges will move freely based on the size of the ultimate view they manage.

For example, in Figure 2, the stack view’s left, top, and right edges are pinned relative to its superview. Using UIStackViewDistributionFill distribution causes its content to resize to fill its width, and since the text field has a lower content compaction priority than the label, it will be stretched when necessary.

Figure 2. Defining the dimensions along the stack view’s axis

Defines the dimensions perpendicular to the stack view’s axis. This is similar to the previous example, but you pin two edges perpendicular to the stack view’s axis and one edge along the axis. This allows the stack view to expand or shrink along its axis as you add or remove views it manages. Unless you use UIStackViewDistributionFillEqually distribution, the managed views will be resized according to their original size. Views perpendicular to their axis will be tiled within their defined range according to the alignment mode of their stack view.

For example, Figure 3 shows a vertical stack view that contains four labels and a button. This stack view uses an 8-point gap and UIStackViewAlignmentCenter alignment. The height of the stack view will grow or shrink as the elements inside the stack increase or decrease.

Figure 3. Defining dimensions perpendicular to the stack view axis

You also define the position and size of the stack view. Here you pin all four edges of the stack view. The stack view will tile its content within the bounds provided. For example, Figure 4 shows a vertical stack view with all four edges pinned relative to its superview. By using the UIStackViewAlignmentCenter alignment and the UIStackViewDistributionFill distribution, the stack view ensures that its content will fill the screen horizontally and vertically. However, getting the desired layout requires two additional steps. By default, the stack view vertically stretches the label but not the image. To scale the image control, lower its content compact priority to below that of the label. Additionally, to maintain the image’s aspect ratio when it scales, you must set the image view’s mode to Aspect Fit. Adding an equal width constraint between the image view and the stack view will help ensure that the image will scale to fill the available bounds.

Figure 4. Defining both the position and size of the stack view

5. Managing the Display of Stack Views

UIStackView is a non-rendering subclass of UIView. It does not provide any user interface of its own. Instead, it only manages the position and size of the views it manages. Therefore, some properties (such as backgroundColor) are invalid on stack views. Similarly, you cannot override layerClass, drawRect: or drawLayer:inContext: methods.

There are a number of properties that define how the stack view tiles its content.

The axis attribute determines the orientation of the stack, which can be either vertical or horizontal.

The distribution property determines the layout of the managed views along its axis;

The alignment property determines the layout of the managed views perpendicular to their axis.

The spacing property determines the minimum gap between the views it manages;

The baselineRelativeArrangement property determines whether the vertical spacing between its views is measured from the baseline;

The layoutMarginsRelativeArrangement property determines whether the stack view should refer to its layout margins when tiling the views it manages.

Typically, you use a stack view to lay out a small number of views. You can create more complex view hierarchies by nesting multiple stack views within other stack views. For example, Figure 5 shows a vertical stack view that contains two horizontal stack views. Each horizontal stack view contains a label and a text field.

Figure 5. Nested Stack views

You can also fine-tune the presentation of a managed view by adding additional constraints to the managed view. For example, you can use constraint classes to set a minimum or maximum height or width for a view. Or you can define an aspect ratio. The stack view uses these constraints when tiling its content. For example, in Figure 4, an aspect ratio constraint on the image view enforces a constant aspect ratio when the image is scaled.

Note: Be careful to avoid incoming conflicts when adding constraints to views within a stack view. As a rule of thumb, if a view’s size in a given dimension defaults back to its native content size, then you can safely add constraints in that dimension.

6. Maintain the unity between the managed views and subviews

The stack view ensures that its arrangedSubviews property will always be a subset of its subviews property. Specifically, the stack view enforces the following:

Whenever the stack view adds a view to its arrangedSubviews array, it will also add that view as a subview, if it hasn't already.

Whenever a subview is removed from the stack view, the stack view also removes it from the arrangedSubviews array.

Removing a view from arrangedSubviews does not remove it as a subview. The stack view will no longer manage the size and position of the view, but the view will still be part of the view hierarchy and will still be rendered to the screen when it is visible.

While the arrangedSubviews array always contains subsets of the subviews array, the order of these arrays remains independent.

The order of the arrangedSubviews array defines the order in which the views are presented in the stack. For horizontal stack views, the views are tiled in reading order, with views with lower indexes to the left of views with higher indexes. For vertical stack views, the views are tiled from top to bottom, with views with lower indexes on top of views with higher indexes.

The order in the subviews array defines the order in which the subviews appear on the Z axis. If views overlap, subviews with smaller indices appear behind subviews with larger indices.

7. Dynamically change the Stack view content

The stack view automatically updates its layout when views are added, removed, or inserted into the arrangedSubviews array, or when the hidden property of a managed subview changes.

The OC code is as follows:

  1. // Appears to remove the first arranged view from the stack.  
  2. // The view is still inside the stack, it's just no longer visible, and no longer contributes to the layout.  
  3. UIView * firstView = self.stackView.arrangedSubviews[ 0 ];
  4. firstView.hidden = YES;

The Swift code is as follows:

  1. // Appears to remove the first arranged view from the stack.  
  2. // The view is still inside the stack, it's just no longer visible, and no longer contributes to the layout.  
  3. let firstView = stackView.arrangedSubviews[ 0 ]
  4. firstView.hidden = true  

The stack view also automatically responds to changes to any of its properties. For example, you can update the stack view’s axis property to dynamically change its orientation.

The OC code is as follows:

  1. // Toggle between a vertical and horizontal stack  
  2. if (self.stackView.axis == UILayoutConstraintAxisHorizontal) {
  3. self.stackView.axis = UILayoutConstraintAxisVertical;
  4. } else {
  5. self.stackView.axis = UILayoutConstraintAxisHorizontal;
  6. }

The Swift code is as follows:

  1. // Toggle between a vertical and horizontal stack  
  2. if (self.stackView.axis == UILayoutConstraintAxisHorizontal) {
  3. self.stackView.axis = UILayoutConstraintAxisVertical;
  4. } else {
  5. self.stackView.axis = UILayoutConstraintAxisHorizontal;
  6. }

For changes to the hidden property of managed subviews and changes to stack view properties, you can animate these changes by wrapping them in an animation block.

The OC code is as follows:

  1. // Animates removing the first item in the stack.  
  2. [UIView animateWithDuration: 0.25 animations:^{
  3. UIView * firstView = self.stackView.arrangedSubviews[ 0 ];
  4. firstView.hidden = YES;
  5. }];

The Swift code is as follows:

  1. // Animates removing the first item in the stack.  
  2. UIView.animateWithDuration( 0.25 ) { () -> Void in
  3. let firstView = stackView.arrangedSubviews[ 0 ]
  4. firstView.hidden = true }

Finally, you can define specific "size class" type values ​​for many stack view properties directly in Interface Builder. The system will animate these changes when the stack view's size class changes.

8. Commonly used methods

Creating a Stack View

  1. - initWithArrangedSubviews: (New in iOS 9.0 )

Managing Scheduled Subviews

  1. - addArrangedSubview: (New in iOS 9.0 )
  2. arrangedSubviews Property (New in iOS 9.0 )
  3. - insertArrangedSubview:atIndex: (New in iOS 9.0 )
  4. - removeArrangedSubview: (New in iOS 9.0 )

Setting up the layout

  1. alignment Property (New in iOS 9.0 )
  2. axis Property (New in iOS 9.0 )
  3. baselineRelativeArrangement Property (New in iOS 9.0 )
  4. distribution Property (New in iOS 9.0 )
  5. layoutMarginsRelativeArrangement Property (New in iOS 9.0 )
  6. spacing Property (New in iOS 9.0 )

constant

  1. UIStackViewDistribution
  2. UIStackViewAlignment

[Editor: chenqingxiang TEL: (010) 68476606]

<<:  Why has iOS 8 become Apple's most vulnerable system?

>>:  iOS 9: Getting Started with UIStackView

Recommend

Song Mosquito's original CG tutorial - Snow Mountain Pine Forest V2 version

Course Catalog ├──01 Spring scene | ├──Section 10...

Google reportedly secretly plans to add cloud computing services

According to Fortune, sources say Google is secre...

Turtle Class·Taobao Virtual No-Source E-commerce Course 5

The course comes from the 1st, 4th and 5th editio...

Can eating rice cause allergies? Do you know these strange allergens?

recently Artist Guo Biting revealed her troubles ...

Phoenix.com advertising resources and techniques

Phoenix Online integrates three platforms: the co...

Why are men more susceptible to COVID-19, SARS and MERS?

The reason why the new coronavirus "favors&q...

10 hot topics that will definitely become popular on Douyin

Hot Template 01: "A Decade of XXX" For ...