IOS 9: getting started with UIStackView and getting started with iosuistackview

Source: Internet
Author: User

IOS 9: getting started with UIStackView and getting started with iosuistackview
IOS 9: getting started with UIStackView

Like every iteration of iOS, iOS 9 brings many new features. Every version of The UIKit framework is changing, and UIStackView is especially used in iOS 9. It will fundamentally change the way developers create user interfaces on iOS. This article will show you how to use UIStackView to create a user interface.


This document assumes that you are familiar with the basics of Auto Layout. If you are not familiar with it, you can first look at the Auto Layout tutorial. To understand why Stack View is so useful and how it works, you must first have an in-depth understanding of Auto Layout.

1. instance Preview

We will use UIStackView to simulate an app scoring prompt. You can add stars or remove stars to score. It looks like this.

Download the sample project from GitHub and open it. There are two Stack views in Main. Storyboard.

We will use these two Stack views to layout the interface. Before coding, let's take a look at how Stack View works.

2. UIStackView Overview

The core of Stack View is to facilitate the allocation of multiple subviews vertically or horizontally. If you have been developing Android, It is very similar to the LinearLayout control.

Stack View automatically creates and adds Auto Layout constraints for each subview. Of course, you can control the size and position of the subview. You can configure the size, layout, and spacing of the subview with options.

Layout content

Open Main. Storyboard, select a Stack View to View its options, and select a Stack View. In Attributes Inspector, pay attention to the options listed below the Stack View.

Axis indicates whether the Stack View subview is horizontal or vertical. Alignment controls the subview Alignment. Distribution defines the subview Distribution mode. Spacing is the minimum Spacing between subviews.

To simplify the terminology, you can understand that Alignment is used to control the X and Y values, while Distribution is used to control the height and width. The other two values affect alignment. If Baseline Relative is selected, the Vertical spacing is adjusted based on the subview Baseline. If Layout Margins Relative is selected, the standard boundary is blank to adjust the subview position.

Another thing to remember is that Stack View is treated as a Container View. Therefore, it is a non-rendered UIView subclass. Unlike other UIView subclasses, it is rendered to the screen. This also means that setting the backgroundColor attribute or reloading the drawRect method will not produce any effect.

SubView and arrangedSubView

Before using Stack View, let's take a look at the differences between its attributes subViews and arrangedSubvies. If you want to add a subview to Stack View Management, you should call addArrangedSubview: or the insertArrangedSubview: atIndex: arrangedSubviews array is a subset of the subviews attribute.

To remove the Stack View subview, call removeArrangedSubview: And removeFromSuperview. Removing arrangedSubview is only important to ensure that the Stack View does not manage its constraints, rather than to delete it from the View hierarchy.

Now we have some knowledge about Stack View and start to use it.

3. Configure the Stack View of the vertical layout

Open Main. Storyboard and select the Stack View above. Change Attributes Inspector as follows:

  • Set Alignment to Center

  • Set Distribution to Equal Spacing

  • Set Spacing to 30

This tells the Stack View to add constraints to the subview so that it is vertically centered and symmetric along the axis of the Stack View, and then sets the margin 30 for the subview.

If the size of the subview does not match that of the Stack View content area, the subview is stretched or compressed Based on the compression resistance priorities. This is also true when you add a subview to the Stack View at runtime.

If the layout has any ambiguity, Stack View will adjust the size of the subview step by step based on the index of the subview in arrangedSubviews until it just fits the size of the Stack View.

4. Add a vertical layout Subview to the Stack View

Add a label, an image view, and a button to the Stack View above. The label is at the top, the image view is in the middle, and the button is below. It looks like this after adding:

Next, we will modify the Attributes of the added subview in Attributes Inspector. Convert the label text secret to "How do you likeour app ?", Select Center for Text Alignment. Enter "logo" for the image view Image, and select "Aspect Fit" for "Content Mode. Finally, set the Text of the button to "Add Star !".

Run the app. We can see that we only do a little work, but we have added three subviews that can respond to changes, such as the direction and size class. In fact, you do not need to manually add any constraints.

When the app is running, click the Debug View Hierarchy button at the bottom of the Xcode window for Real-Time View debugging.

Select any added subview. Check the size inspector. We noticed that the Stack View has automatically added constraints to it. The constraints added for the button are displayed.

5. Add a star

Button events are not associated with the app interface. We will associate them first. Stop running the app and open storyboard. Create a Touch Up Inside event associated with an IBAction named addStar to the button.

AddStar (_ :) method implementation:

1234567 @IBAction func addStar(sender: AnyObject) {    let starImgVw:UIImageView = UIImageView(image: UIImage(named: "star"))    self.horizontalStackView.addArrangedSubview(starImgVw)    UIView.animateWithDuration(0.25, animations: {        self.horizontalStackView.layoutIfNeeded()    })}

Add an animation to the star image in the Stack View of the horizontal layout. Remember, since Stack View automatically manages Auto Layout constraints for us, we can only call layoutIfNeeded for animation.

Compile and run the app and click add star. The final result is not satisfactory.

Select the Stack View below to View Attributes Inspector. The problem is displayed. Since both Alignment and Distribution are set to Fill, Stack View stretched the stars to fit their size.

This will cause more problems when adding more stars. We want the stars to be centered rather than stretched to fit the width of the Stack View.

Change Alignment to Center and Distribution to Fill Equally. Finally, set the image view content in the addStar (_ :) method.

12345678 @IBAction func addStar(sender: AnyObject) {    let starImgVw:UIImageView = UIImageView(image: UIImage(named: "star"))    starImgVw.contentMode = .ScaleAspectFit    self.horizontalStackView.addArrangedSubview(starImgVw)    UIView.animateWithDuration(0.25, animations: {        self.horizontalStackView.layoutIfNeeded()    })}

Run the app and click the Add button several times. We can see that all the stars are in the center.

6. Stack View nesting

You cannot delete stars. Our app scores are of little use. Open storyboard and add a horizontal Stack View to the Stack View above. Place it under the logo and above the button.

Add "Add Star !" Drag the button to the newly added Stack View and add a button to the new Stack View. Change the title of the button to "Remove Star", and set the text color to red. Preview as follows:

Edit the Attributes of the new Stack View in Attributes Inspector. The changes are as follows:

  • Set Alignment to Center

  • Set Distribution to Equal Spacing

  • Set Spacing to 10

7. delete a star

Create an IBAction response method named removeStar for the Remove Star button and the event type is Touch Up Inside.

RemoveAction (_ :) implementation:

1234567891011 @IBAction func removeStar(sender: AnyObject) {    let star:UIView? = self.horizontalStackView.arrangedSubviews.last    if let aStar = star    {        self.horizontalStackView.removeArrangedSubview(aStar)        aStar.removeFromSuperview()        UIView.animateWithDuration(0.25, animations: {            self.horizontalStackView.layoutIfNeeded()        })    }}

You can add or delete an app. Change the direction of the simulator or rotate the device to see how the app adjusts its interface. We have built the app user interface without adding a line of constraints.

Note that removeFromSuperview is called in removeStar (_ :) to remove the subview from the view level. Calling removeArrangedSubview (_ :) again only tells the Stack View that it no longer needs to manage subview constraints. The subview will remain in the view hierarchy until removeFromSuperview is called to remove it.

Conclusion

The UIStackView class greatly simplifies user interface development. This is a good thing, especially as hardware changes. The use of UIStackView reduces the developer's boring constraints for simple scenarios and handed over complicated work to UIKit.

If you are interested in any knowledge points in this article, you can download the complete project from GitHub.

Related Article

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.