IOS9-by-Tutorials-Study Notes 6: UIStackView-Auto-Layout-Changes

Source: Internet
Author: User

IOS9-by-Tutorials-Study Notes 6: UIStackView-Auto-Layout-Changes
IOS9-by-Tutorials-Study Notes 6: UIStackView-Auto-Layout-Changes

Today, this is the sixth note. Now I have no idea that I can update it to the sixth one. I am a lazy person, and I don't like coding very much now. When writing these notes, I need to read the English document and test the code, so I have to consider how to write it clearly. Here, it is explained that my English level is only level 4, and the Chinese level can only be evaluated in a pleasant way. It is inevitable that the statements in the article will not be fluent and I hope to clearly express the meaning.

When I have a lot of gossip, I will go back to the topic. This article introduces the UIStackView and some Auto Layout changes.

I personally understand UIStackView to solve the situation where the constraints added by using Storyboard need to change frequently. I think we may all have encountered modification constraints during development. Generally, we link the constraints with an outlet constraint and then modify the code. However, this operation is inconvenient. UIStackView automatically adjusts the internal display of UIStackView by modifying some simple attributes, such as alignment, distribution, and spacing.

The changes to Auto Layout are mainly about layout anchors and layout guides.

Getting Started

Open the related project VacationSpots in this chapter and run it on the iPhone 6 simulator. You can see that the APP has some UI problems. Don't worry, these problems will be fixed later. The problem is as follows:
1. The content marked in the figure is not centered vertically.

Click London Cell in the list to go to the details page. The following three buttons do not evenly allocate space:

Click the hide button next to WEATHER. The content is hidden but left blank. The following content is not moved up:

What to see is more reasonable under why visit.

Now that you have understood these problems, you can use UIStackView to modify them. Open Main. storyboard and view the following Controller scene:

We can note that each of the preceding controls has a background color, which is only used to help us check the changes to these attributes. These background colors will be removed during running. You can use the following code to comment out these codes when you want them to run: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Vcd4nc1_vymxvy2txdw90zt4ncjxwcmugy2xhc3m9 "brush: java;"> // SpotInfoViewController.swift override func viewDidLoad() { super.viewDidLoad() // Clear background colors from labels and buttons for view in backgroundColoredViews { view.backgroundColor = UIColor.clearColor() } ........ }

The controls in Storyboard are all associated with the corresponding attributes in SpotInfoViewController. swift through outlet. The name displayed on the storyboard corresponds to the variable SpotInfoViewController. swift.

Your first stack view

We first use Stack View to solve the button at the bottom of our problem list. You can use UIStackView to allocate space between the position and the control on a coordinate extraction. Fortunately, it is not too difficult to embed Views into UIStackView. In the Storyboard, select the following three button controls for Spot Info View Controller:

After selecting the three buttons, click the following button in the Storyboard:

When Views are embedded in UIStackView, the constraints of Views are removed, and the constraints of UIStackView need to be set. Select UIStackView and add constraints as follows:

Here is a tip for selecting UIStackView. Because UIStackView is behind the button, it is difficult to select it. We can press Shift and right-click it, in the displayed menu, list all views in the current click position. You can select UIstackView. Another method can be selected in outline view.

After the constraints are set, the button is displayed as follows. The first button is stretched and the space remaining in UIStackView is filled. UIstackView has a Distribution attribute, which is used to control how Views are displayed in UIStackView. Now Fill is set, and UIStackView will be filled up soon. For this purpose, UIstackView will stretch the View based on its ccontent hugging priority, and the lowest will be stretched. If the priority is the same, the first one will be stretched.

The purpose is to make the distance between views Equal and change Distribution to Equal Spacing in Attributes inspector.

When you run the APP, we can see that our buttons are correctly displayed:

Some Thoughts

Think about the "Pleasant" behavior of Using Auto Layout to meet the above requirements through constraints. Maybe you are familiar with Auto Layout and think that all these things are very simple. So you are thinking about how to add and delete a button if we need to add a button next to it? Are the constraints deleted and re-added? If you use UIStackView, this will become easier. As long as we add or delete the View, other work UIstackView will help us.

UISTackView will be further explained in the next article. Here we will first introduce the new features of Auto Layout: layout anchors and layout guides.

Layout anchors

Layout anchors provides a simple way to create constraints.

Imagine that we created a constraint before iOS 9, which is simply tianshu, but using Layout anchors in iOS 9 will be much simpler. The following are two comparisons:

// Let constraint = NSLayoutConstraint (item: topLabel, attribute :. bottom, relatedBy :. equal, toItem: bottomLabel, attribute :. top, multiplier: 1, constant: 8) // iOS 9let constraint = topLabel. bottomAnchor. constraintEqualToAnchor (bottomLabel. topAnchor, constant: 8)

Layout anchors is easy to understand and write.

The attribute corresponding to the constraint we added before iOS 9 has basically corresponding anchor, for example, top corresponds to topAnchor, and bottomAnchor corresponds to bottomAnchor. Layout Anchor is directly or indirectly inherited from NSLayoutAnchor. The above only demonstrates equality. We all know that it is greater than or equal to the constraint. The NSLayoutAnchor interface files are listed below, you can clearly understand the corresponding methods in the interface file:

import Foundationimport UIKit/*  NSLayoutAnchor.h    Copyright (c) 2015, Apple Inc. All rights reserved.*//* An NSLayoutAnchor represents an edge or dimension of a layout item.  Its concrete  subclasses allow concise creation of constraints.      Instead of invoking  +[NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:]  directly, you can instead do something like this: [myView.topAnchor constraintEqualToAnchor:otherView.topAnchor constant:10]; The -constraint* methods are available in multiple flavors to support use of different relations and omission of unused options. */@available(iOS 9.0, *)public class NSLayoutAnchor : NSObject {    /* These methods return an inactive constraint of the form thisAnchor = otherAnchor.     */    public func constraintEqualToAnchor(anchor: NSLayoutAnchor!) -> NSLayoutConstraint!    public func constraintGreaterThanOrEqualToAnchor(anchor: NSLayoutAnchor!) -> NSLayoutConstraint!    public func constraintLessThanOrEqualToAnchor(anchor: NSLayoutAnchor!) -> NSLayoutConstraint!    /* These methods return an inactive constraint of the form thisAnchor = otherAnchor + constant.     */    public func constraintEqualToAnchor(anchor: NSLayoutAnchor!, constant c: CGFloat) -> NSLayoutConstraint!    public func constraintGreaterThanOrEqualToAnchor(anchor: NSLayoutAnchor!, constant c: CGFloat) -> NSLayoutConstraint!    public func constraintLessThanOrEqualToAnchor(anchor: NSLayoutAnchor!, constant c: CGFloat) -> NSLayoutConstraint!}/* Axis-specific subclasses for location anchors: top/bottom, leading/trailing, baseline, etc. */@available(iOS 9.0, *)public class NSLayoutXAxisAnchor : NSLayoutAnchor {}@available(iOS 9.0, *)public class NSLayoutYAxisAnchor : NSLayoutAnchor {}/* This layout anchor subclass is used for sizes (width & height). */@available(iOS 9.0, *)public class NSLayoutDimension : NSLayoutAnchor {    /* These methods return an inactive constraint of the form         thisVariable = constant.    */    public func constraintEqualToConstant(c: CGFloat) -> NSLayoutConstraint!    public func constraintGreaterThanOrEqualToConstant(c: CGFloat) -> NSLayoutConstraint!    public func constraintLessThanOrEqualToConstant(c: CGFloat) -> NSLayoutConstraint!    /* These methods return an inactive constraint of the form         thisAnchor = otherAnchor * multiplier.    */    public func constraintEqualToAnchor(anchor: NSLayoutDimension!, multiplier m: CGFloat) -> NSLayoutConstraint!    public func constraintGreaterThanOrEqualToAnchor(anchor: NSLayoutDimension!, multiplier m: CGFloat) -> NSLayoutConstraint!    public func constraintLessThanOrEqualToAnchor(anchor: NSLayoutDimension!, multiplier m: CGFloat) -> NSLayoutConstraint!    /* These methods return an inactive constraint of the form         thisAnchor = otherAnchor * multiplier + constant.    */    public func constraintEqualToAnchor(anchor: NSLayoutDimension!, multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint!    public func constraintGreaterThanOrEqualToAnchor(anchor: NSLayoutDimension!, multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint!    public func constraintLessThanOrEqualToAnchor(anchor: NSLayoutDimension!, multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint!}

In the preceding interface file, we can clearly understand that NSLayoutAnchor has three subclasses: NSLayoutXAxisAnchor, NSLayoutYAxisAnchor, and NSLayoutDimension. The Anchor types of UIView are listed below:

extension UIView {    /* Constraint creation conveniences. See NSLayoutAnchor.h for details.     */    @available(iOS 9.0, *)    public var leadingAnchor: NSLayoutXAxisAnchor { get }    @available(iOS 9.0, *)    public var trailingAnchor: NSLayoutXAxisAnchor { get }    @available(iOS 9.0, *)    public var leftAnchor: NSLayoutXAxisAnchor { get }    @available(iOS 9.0, *)    public var rightAnchor: NSLayoutXAxisAnchor { get }    @available(iOS 9.0, *)    public var centerXAnchor: NSLayoutXAxisAnchor { get }    @available(iOS 9.0, *)    public var topAnchor: NSLayoutYAxisAnchor { get }    @available(iOS 9.0, *)    public var bottomAnchor: NSLayoutYAxisAnchor { get }    @available(iOS 9.0, *)    public var firstBaselineAnchor: NSLayoutYAxisAnchor { get }    @available(iOS 9.0, *)    public var lastBaselineAnchor: NSLayoutYAxisAnchor { get }    @available(iOS 9.0, *)    public var centerYAnchor: NSLayoutYAxisAnchor { get }    @available(iOS 9.0, *)    public var widthAnchor: NSLayoutDimension { get }    @available(iOS 9.0, *)    public var heightAnchor: NSLayoutDimension { get }}

The Anchor attribute of UIView is divided into three types. Similarly, when setting attributes, we also need to set attributes of the same type, such as the constraints between ViewA and ViewB, viewA-topAnchor and ViewB-bottomAnchor are acceptable. ViewA-topAnchor and ViewB-leftAnchor are not allowed. In this case, the compiler will warn you that an error will also be reported during the runtime.

Note: whyVisitLabel. topAnchor. constraintEqualToAnchor (whatToSeeLabel. leftAnchor) according to the above statement, an error should be reported, but I did not report an error during running. Maybe it is because I just wrote a test, in the future, I will continue to test this knowledge point and then correct it.

Layout guides

Sometimes we want to set the space between two views, we need to add an invisible View (dummy View) between the two views, and then set constraints. Layout guide can be understood as an invisible View. We can use its rectangular edge for Layout, and we can set constraints like we use View. The advantage of using Layout guide is that it is lightweight and does not participate in the Event Response Process at the view level. The layout guide also contains all Views except firstBaselineAnchor and lastBaselineAnchor.

Fixing the alignment bug

In the following example, layout guide is used to solve the problem where the text content on the list page is not in the upper or lower state. The constraint we set is that the distance between the label and the above is 15. It is normal that the current label shows a row. If there are two rows, since the above constraints are fixed, they will eventually become a result of no particular choice.

Before iOS 9, we want to solve this problem by placing the two labels in a container view container and setting the container view as the play, the container view is an invisible view, namely, dummy view. Now we can use layout guide on iOS 9 to replace this view.

Currently, you can only add layout guide using code. Open the VacationSpotCell. swift file and modify the corresponding code:

Override func awakeFromNib () {super. awakeFromNib () // TODO: Add layoutGuide code here to center the name and locationName labels vertically // create layou guide let layoutGuide = UILayoutGuide () contentView. addLayoutGuide // sets the constraint of layout guide. let topConstraint = layoutGuide. topAnchor. constraintEqualToAnchor (nameLabel. topAnchor) let bottomConstraint = layoutGuide. bottomAnchor. constraintEqualToAnchor (locationNameLabel. bottomAnchor) let centerConstraint = layoutGuide. centerYAnchor. constraintEqualToAnchor (contentView. centerYAnchor) // activate the constraint NSLayoutConstraint of layout guide. activateConstraints ([topConstraint, bottomConstraint, centerConstraint])}

Some text was truncated when the APP was run:

Handle truncation issues

This is because we set the layout guide to center, but the constraint between nameLabel (above) and super view top still exists, causing the label below to be squashed, at this time, we only need to delete this constraint. However, after the storyboard is deleted, an error is prompted. In this case, the placeholder constraint can be used to prevent the storyboard from reporting errors and will not be used during running.

I 've been working overtime recently. I 've finally finished this article for a long time. It may be wrong. Please also point it out.

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.