Uistackview Tutorial: Understanding Stack View

Source: Internet
Author: User
Tags compact

  • Original link: Uistackview tutorial:introducing Stack views
  • Original Author: Jawwad Ahmad
  • Development technology Front www.devtf.cn
  • Translator: Kmyhy

Ray NOTE: Congratulations! To promote IOS 9 Feast, the first part of the book has been unlocked for you. This article comes from a section in IOS 9 tutorials, which is a simplified version of this section that allows you to glimpse the contents of the book. I wish you a pleasant reading!

Every family has a hard-to-read Sutra. Now there is a new requirement for you to add or delete a view at run time, which requires us to reposition the neighboring view.

What would you do? Maybe you'll create a new layout constraint connection in the storyboard so you can install or uninstall some of these constraints? Or would you use a third-party library to implement it? Or do you see the complexity of the task completely implemented in code?

Perhaps all views in the view tree near the view do not need to be changed at run time, but when you add a new view to the storyboard, you still have to find ways to squeeze it out of space.

Have you ever had a time when you would have to clear all the constraints and re-add the constraints all at once because you felt that the layout constraint conflicts to be solved were too tricky.

Through the introduction of Uistackview, the completion of the above task becomes insignificant. Stack view provides a way to lay out a horizontal or vertical view of multiple views. By making simple settings for several properties, such as alignment, distribution, and spacing, you can let the view that it contains fit into its effective space.

Note: The Uistackview tutorial assumes you have a basic grasp of automatic layout. If you are not yet familiar with automatic layout, refer to "Automatic Layout Tutorial: Part 1th".

Begin

In this tutorial, you will create an app called vacation spots. The app is simple enough to show you a list of places that can make you all the more.

Don't be too busy packing, because this app has a few questions you need to use stack view to solve, of course, this is easier than you use automatic layout to solve the more simple.

First download the Start Project for this tutorial, and then run it on the iphone6s.

Click on the London cell to jump to the introduction page

At a glance, this page seems to be OK, but it actually has these problems.

View the row of buttons below the view. Their current positions are arranged in a fixed spacing, so they cannot accommodate changes in screen widths. To see the problem, you just press the command+ left arrow to rotate the simulator screen to a horizontal screen.

Click the Hide button next to weather. It successfully hides the text, but the content underneath it remains in its original position, leaving a large blank area.

The order of each section should also be adjusted. It would be better if you put the "what-see" section to the right of the "Why visit" section, rather than inserting the "wheather" section between the two.

In landscape mode, a row of buttons on the bottom is too close. If you are in landscape mode, it is better to narrow the distance between the sections.

Now that you know what you're going to do, it's time to get into the project and work on it.

Open the Main.storyboard and find the scene of Spot Info View controller. Wow! There are a lot of colors on your stack view!

These labels and buttons are set to a different background color to make the effect more intuitive at run time. It is in the storyboard that it also helps to see changes in the Stack view property causing its internal view to change.

If you want to see these colors when you run the app, you can annotate the following statements in the Spotinfoviewcontroller viewdidload () method. Now, of course, you don't have to do this:

fromand buttons// 清空标签和按钮的背景色forin backgroundColoredViews {  view.backgroundColor = UIColor.clearColor()}

At the same time, all connected outlet tags have a hint text that indicates the name of the outlet variable to which they are connected. This will indicate which label is at run time. For example, a label with a typeface will be connected to the following outlet variable:

weakvar whyVisitLabel: UILabel!

Also note that the size of the scene in the storyboard is not the default 600x600 when the size class is enabled.

The size class is still available, but in the properties panel of the initial navigation controller, the Size property under simulated metrics is set to iphone 4-inch. This is just to make it easier for us to use the storyboard, the simulated metrics property has no effect at run time-the size of the view on different devices will still change automatically.

First Stack View

The first thing we need to do is the spacing between the bottom row of buttons. A stack view distributes the view it contains in a variety of ways along its axis, and it can also distribute the view equidistant in a certain direction.

Fortunately, adding an existing view to a new stack view is not much of a complication. First, use the command+ left button to select all the buttons in the bottom row of the spot Info View controller:

If the outline view is not open, first click the Show Document outline button in the lower left corner of the storyboard canvas to open the outline view:

See if 3 buttons are selected in the outline view:

If not all selected, you can still use the command+ left button to re-select them in the outline view.

Once you've selected these 3 buttons, find the new stack button in the lower left corner of the storyboard canvas and click on it:

These buttons will be embedded in a new stack view:

3 buttons Now one is squeezing one--you will soon solve the problem.

Although Stack view manages the location of these buttons, it still requires us to add automatic layout constraints to it.

When you add a view to a stack view, any constraints relative to the other view are deleted. With the previously added button as an example, the Submit rating button has a vertical spacing constraint relative to the bottom of the rating label:

Now click on the Submit Rating button to see that it has lost all constraints:

Another way to verify that these constraints have been removed is to use the size panel to view (??). 5):

To add a layout constraint to a stack view, you first need to select it. It's still hard to pick a stack view that's full of child views on the storyboard.

One simple way to do this is to select the stack view in the outline view:

Another technique is to press the shift+ right or control+shift+ left button (if you're using a trackpad) anywhere in the stack View. A context menu pops up, listing the view tree at the point where you clicked, and you can select Stack view from this menu.

Now, we use the shift+ right-click method to select the stack View:

Then click the Pin button in the Auto Layout toolbar to add a constraint:

First tick constrain to margins. Then add the following constraints around the stack view:

Top20, Leading: 0, Trailing: 0, Bottom: 0

Double-check the numbers in top, leading, trailing, bottom, and make sure that their I-bars are selected. Then click Add 4 Constraints:

Stack view now has the correct dimensions, but it stretches the size of the first button so that it fills all remaining space:

The property that determines how stack view distributes its subview along the axis is its distribution property. Currently, the value of this property is fill, which means that the subview will occupy the stack View entirely along the axis. Therefore, Stack view stretches one of the subview to fill the remaining space, especially the one with the lowest horizontal content priority, and if all subview have the same priority, the first subview is stretched.

Of course, you don't want the buttons to fill the entire stack view-you want them to be spaced evenly.

Make sure that stack view is selected and open the Properties panel. Modify the Distribution property from fill to equal Spacing:

Compile run, click on a cell, rotate the simulator (? →). You will see the next row of buttons now arranged in equal spacing!

If you do not use Stack view, this solves the problem by separating the buttons with a blank view and placing some Spacer view between the buttons to separate the spaces. All spacer view will add equal width constraints and many additional constraints to make these spacer view layouts correct.

This looks as shown. For the sake of visualization, the background color of these spacer view is set to light gray:

Once you have to do this in the storyboard, it can cause a lot of problems, especially when many views are dynamic. If you want to add a button at run time or hide/delete a button, it's really not easy to adjust these spacer view and constraints.

To hide the view in a stack view, you only need to set the view's hidden property to True, and the remaining work stack view will be done by itself. This is also our main idea of solving the text under the user's hidden weather tag. Later in this article, when you add the weather tag to stack view, we'll cover the issue.

Convert each section to a stack View

We will add all the sections in the Spotinfoviewcontroller to the stack view. This will help us complete the rest of the task. Next we'll adjust the rating section.

Rating section

Just above the stack view that you created earlier, choose the Rating tab, along with the label that appears next to several star icons:

Then click the Stack button to embed them in a stack view:

Then click the Pin button. Tick constrain to margins and add the following constraint:

Top20, Leading: 0, Bottom: 20

Open the Properties panel and set the spacing to 8:

You may see a layout constraint warning for misplaced views, and the star tag will be stretched beyond the view:

Sometimes Xcode will temporarily prompt for warnings, or the location of the stack view is incorrect, and the warnings will disappear after you add additional constraints. You can completely ignore these warnings.

To resolve this warning, we can modify the frame of the stack view and then change it back, or temporarily modify one of its layout constraints.

Let's try. First change the Alignment property from fill to top, and then back to the original fill. You will see that the star tag shows up properly:

Compile, run, and test.

Dissolve a stack View

Before you continue, take some "first aid" training. Sometimes you find that some stack view is no longer needed, possibly because it is outdated, the code is refactored, or just a whim.

Fortunately, there is an easy way to dissolve a stack View.

First, select the stack View you want to dissolve. Press the OPTION key and click the Stack button. This will bring up a context menu and then click unembed:

Another way to dissolve is to select Stack View and then click the Editor\unemebed menu.

Vertical Stack View

Next, you will create a vertical stack View. Select the why visit label and the following label:

Xcode automatically infers that this will be a vertical stack View based on the location of the two. Click the Stack button to embed both into a stack View:

The following label originally had a right margin of the view constraint, but was removed after it was embedded in the stack view. Now, this stack view is not constrained, so it automatically adapts to the width of the widest of two tags.

Select Stack View and click the Pin button. Tick constrain to margins, set top, leading, trainling to 0.

Then, click the drop-down button to the right of bottom and select weather (curent distance =20) from the list:

By default, the constraint is the closest object relative to the distance, and for the bottom constraint is the Hide button that is 15 pixels away from it. But we're actually trying to make the constraint relative to the weather tag.

Finally click the Add 4 Constraints button. The display results are as follows:

Now that we have the second stack View, the right side of it is aligned to the right side of the view. But the bottom label is still the original width. You will then modify the alignment property of the stack view to resolve the problem.

Alignment Property

The Alignment property determines how stack view places its subview vertically along its axial direction. For a vertical stack View, this property can be set to fill, leading, center, and trailing.

For a horizontal stack View, this property is slightly different:

. Top replaced. Leading,.bottom replaced. Trailing. In addition, the horizontal stack view has two more property values:. Firstbaseline and. Lastbaseline.

This is the result of setting the alignment to a different property value for the vertical stack View:

Fill:

Leading:

Center:

Trailing:

When you have finished testing the layout effect for all alignment values, modify the alignment to fill:

Then the compilation runs and the test is normal.

Set alignment to fill to indicate that all view will be fully occupied along the direction perpendicular to the stack view axis. This makes the why visit label extend its width to 100%.

What if we just want the bottom label to extend the width to 100%?

This problem does not seem to be much of a problem now, because the background color of the two labels at run time is transparent. But it's different for the weather section.

We'll use a different stack view to illustrate the problem.

Replace "What's see" with a stack View

This section is similar to the previous one, so we'll take a brief look at it.

1. First, check the "what" tab and tags.

2. Click the Stack button.

3. Click the Pin button.

4. Tick constrain to margins and add 4 constraints:

Top:20, leading:0, trailing:0, bottom:20

5. Set the alignment of the stack view to fill.

Now your story board looks like this:

Compile the run and test for any changes.

Now it's only the weather section left.

Convert weather section to stack View

The weather section is a bit more complicated because it has a hide button.

One approach is to use a nested stack view to embed the weather tag and the hide button into a horizontal StackView, and then embed the stack view and tag into a vertical stack view.

It looks like this:

Note that the weather label is stretched to the same height as the Hide button. This is not appropriate because it causes a bit more space between the weather label and the text below.

Note the Alignment property is responsible for the layout of the stack view axis in the vertical direction. So, we need to set the Alignment property to Bottom:

But we don't want the height of the Hide button to determine the height of the stack view.

The correct way is to have the Hide button do not stay in the same stack view as the weather section, or any other stack view.

In this way, a subview is also retained in the top-level view, and you will add a constraint that is relative to the weather tag--weather tag embedded in the stack view. That is, you want to add a constraint to a button that is outside the stack view, which is relative to a tag in the stack view!

Check weather tags and tags:

Click the Stack button:

Click the Pin button, tick constrain to margins, and add the following constraint:

Top20, Leading: 0, Trailing: 0, Bottom: 20

Set the alignment of the stack view to fill:

We need to add a constraint to the left of the Hide button and to the right of the weather tag so that the width of the weather tag does not fill the entire stack view.

Of course, the bottom label width still needs to be 100% full.

We do this by embedding the weather tag in a vertical stack View. Note that the alignment property of the vertical stack view can be set to. Leading, if you pull the stack view wide, the view inside it will remain left-aligned.

Select the weather label from the outline view, or select the weather tag with the control+shift+ left button:

Then click the Stack button:

To ensure that axis is Vertical, set alignment to leading:

Great! This way the stack view outside will stretch the internal stack view to full fill, while the internal stack view allows the label to remain the original width!

Compile and run. What the hell is this? The Hide button ran to the middle of the text?

This is because the weather tag is embedded in the Stack View, and any constraints between it and the Hide button are removed.

From the Hide button, right-drag a new constraint to the WEATHER label:

Press the SHIFT key while selecting horizontal Spacing and Baseline. Then click Add Constraints:

Compile and run. The position of the Hide button is now right, and when the Hide button is pressed and the label in Stack view is hidden, the view below is also adjusted-no need to manually adjust it at all.

The choice is that some of the sections are in their own stack view, and we're going to put a stack view on the outside of them so that the last two tasks will be easier.

Top Stack View

In the outline view, select the top 5 Stack view with the command+ left button:

Then click the Stack button:

Click the Pin button, tick constrain to margins, and set the 4-edge constraint to 0. Then set the spacing to 20,alignment to Fill. Now the storyboard will look like this:

Compile run:

Oh! This Hide button has lost its restraint again! Because Stack view contains a WEATHER tag, a layer of stack view is added to the outside. This is not a big problem, just like you did before, and then add the constraints again.

Right-drag a constraint from the Hide button to the Weather tab, hold down the Shift key, and select horizontal Spacing and Baseline. Then click Add Constraints:

Compile and run. The Hide button is in the correct position.

Readjust View Location

Now that all of the sections are embedded in a top-level Stack view, we want to change the location of the what-to-see section so that it is behind the weather section.

Select the middle stack view from the Outline view and drag it between the first to second stack view.

Note:keep the pointer slightly to the left of the stack.
You ' re dragging it between so that it remains a subview of the outer
Stack view. The little blue Circle should is positioned at the left
Edge between the "the" and not "on the right edge:

Note: Make the arrows slightly biased to the left of the stack view you are dragging so that it can be added as a subview of the outer stack view. The small blue circle should be located at the left end of the two Stack View instead of the right side:

Now, the weather section is the third section from top to bottom, because the Hide button is not a Stack view subview, so it does not participate in the move, and its frame is currently incorrect.

Click the Hide button to select it:

Then click on the Resolve Auto Layout issues button in the Automatic Layouts toolbar to select Update Frames:

Now the Hide button will return to the correct position:

Well, for you, it's no longer a problem to adjust the position of the view with auto-layout or to re-add the constraint, but why is there a less perfect feeling?

Configuration-based Size class

Finally, there is a task that has not been completed. In the horizontal screen mode, vertical space is more precious, you want to get closer to these sections. To achieve this, you need to determine that when the vertical size class is compact, the spacing property of the top stack view is changed from 20 to 10.

Select the top stack View and click the + button in front of Spacing:

Select any Width > Compact Height:

In the newly emerged Wany hC column, set Spacing to 10:

Compile and run. Spacing does not change in portrait mode. Rotate the simulator (? ←), you will see that the spacing between the sections is reduced, and now the space between the bottom buttons has also become larger:

If you don't add the outermost Stack View, you can still use the Size class to set the vertical spacing between each section to 10, but that's not the only place you can do it.

The rest of the time will be more enjoyable things happen, that is animation!

Animation

Now, when you hide and display weather information, you still feel a bit abrupt. You will add an animation to make this transition smoother.

Stack View fully supports UIView animations. In other words, to animate/hide the subview it contains, simply switch its hidden property in one animation block.

Let's take a look at how the code is implemented. Open Spotinfoviewcontroller.swift and find
Updateweatherinfoviews (hideweatherinfo:animated:) method.

Put the last line of the method:

weatherInfoLabel.hidden = shouldHideWeatherInfo

To be replaced by:

if animated {  UIView.animateWithDuration(0.3) {    self.weatherInfoLabel.hidden = shouldHideWeatherInfo  else {  weatherInfoLabel.hidden = shouldHideWeatherInfo}

Compile and run, click the Hide button or the Show button. Does it look much better after adding an animation?

In addition to animating the hidden property in the view in Stack view, you can also use UIView animations for the properties of the stack view itself, such as Alignment properties, distribution properties, Spacing properties, and Axi S property.

What to do next

You can download the complete sample project from here.

In this Uistackview tutorial, you learned what a Stack View is and its various properties that allow you to lay out its subview. Stack View is highly configurable, and there are often more than one way to achieve the same effect.

The best way to learn is to modify various properties and experience the final effect. Do not test a property individually, but try to experiment with the layout effects of the various properties that match each other.

This tutorial is "IOS 9 Tutorials", chapter 6th, "Uistackview and Auto Layout changes", and the Lite version of chapter 7th, "Intermediate Uistackview". If you want to learn more about the new features of Uistackview and other iOS9, check out this book!

Also, if you have any questions or comments about this article, please join the discussion below!

Uistackview Tutorial: Understanding Stack View

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.