This article is translated by Cocoachina translator Candeladiao, and you are welcome to participate in our translation activities.
Original: IOS 9:getting Started with Uistackview
iOS 9, like every iteration of iOS, brings a lot of new features. Each version of the Uikit framework is changing, while iOS 9 is particularly Uistackview, which will fundamentally change the way developers create user interfaces on iOS. This article will take you through how to create a user interface using Uistackview.
This article assumes that you are already familiar with the Auto Layout Foundation. If you are unfamiliar, you can see the Auto layout tutorial first. To understand why stack view is so useful and how it works, you need to have a deep understanding of auto layout first.
1. Instance Preview
We'll use Uistackview to simulate an app scoring tip. Users can add stars or remove stars to score. It looks like this when it's done.
First download the sample project from GitHub and open it. There are two stack View in Main.storyboard
We will use these two stack view to layout the interface. Before you start coding, let's take a look at how stack view works.
2. Uistackview Overview
The core of Stack view is the convenience of arranging multiple subview vertically or horizontally, which is very similar to the LinearLayout control if you have done Android development.
The most useful thing about Stack view is that it 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, arrangement, and spacing between subview with options.
Layout content
Open Main.storyboard, select one of the stack views to view its options, and select a stack view. In Attributes inspector, note the options listed below stack view.
Axis Indicates whether the stack view Subview is arranged horizontally or vertically. Alignment controls the Subview alignment. Distribution defines how the Subview is distributed. Spacing is the minimum spacing between subview.
To simplify the terminology, you can understand this: Alignment is used to control the x and Y values, while the distribution is used to control the height and width. The other two values will affect the alignment. If baseline relative is selected, vertical spacing is adjusted based on the baseline of the Subview. If layout Margins Relative is selected, the Subview position is adjusted relative to the standard boundary whitespace.
Another need to keep in mind is that Stack view will be treated as container view. So it's a uiview subclass that won't be rendered. Unlike other UIView subclasses, it is rendered to the screen. This also means setting its BackgroundColor property or overloading DrawRect: The method does not produce any effect.
Subview and Arrangedsubview
Before we start using Stack view, let's take a look at the difference between its properties subviews and the Arrangedsubvies property. If you want to add a subview to Stack view management, you should call Addarrangedsubview: or Insertarrangedsubview:atindex: The arrangedsubviews array is a subset of the Subviews properties.
To remove Subview from stack view management, you need to call Removearrangedsubview: and Removefromsuperview. It is important to understand that removing arrangedsubview is just to make sure that stack view no longer manages its constraints, rather than removing it from the view hierarchy.
Now we have a certain understanding of stack view and start using it.
3. Configure the vertical layout of the stack View
Open Main.storyboard Select the stack View above. Make the following changes to attributes Inspector:
This tells the stack view to add a constraint to the subview that is centered vertically and symmetrically along the axis of the stack view, and then sets the margin 30 for the subview.
If the Subview size does not match the Stack view content area, Subview is stretched or compressed according to the compression resistance priorities. This is also true for adding subview to Stack view at run time.
Any ambiguity in the layout stack view will step back from Subview in arrangedsubviews to adjust the size of the subview until it fits exactly the stack view size.
4. Adding a vertical layout to the stack view Subview
Add a label, an image view, and a button to the stack view above. Label on top, Image view in the middle, button below. This looks like this when the add is complete:
Next, we'll modify the properties of the subview that we just added in Attributes Inspector. Put the text of the label into "How does you likeour app?", text alignment Select Center. Image view of image input "logo", Content mode select Aspect Fit. Finally, the button's text is set to "Add star!".
Run the app. I can see that we've only done very little work, but we've added three subview that respond to direction, size class, and so on. In fact, you don't need to add any constraints manually.
When the app is running, click the Debug View Hierarchy button at the bottom of the Xcode window to make real-time view debugging
Select any one of the previously added Subview. Looking at size inspector, we notice that stack view has automatically added a constraint to it. The constraint that is added for the button is displayed
5. Add Pentagram
Button events have not been associated with the app interface, we are connected first. Stop running the app and open storyboard. Create a touch up inside event that is named Addstar ibaction associated 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 ()      } |
Adds an animation to the star image in the horizontal layout stack view. Remember, because stack view automatically manages auto Layout constraints for us, we can only invoke layoutifneeded to animate.
Compile and run the app and click the Add Star button. To see the final result is unsatisfactory.
Select the following stack view to see Attributes inspector see the problem. Since both alignment and distribution are set to Fill,stack View, the stars are stretched to fit their size.
This can cause more problems when adding more stars. We want the stars to be centered instead of being stretched to fit the width of the stack view.
Modify the value of alignment to center, and modify the value of distribution to fill equally. Finally, set the contents of the image view 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, click the Add button several times and we find all the stars centered.
6. Stack View Nesting
Can't delete stars, our app rating what's not very useful. Open Storyboard and add a stack view with a horizontal layout to the stack view above. Place it under the logo, above the button.
Put "Add star!" Button onto 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. The preview is as follows:
To edit the properties of the new stack view in Attributes Inspector, change the following:
7. Delete Pentagram
Create a Ibaction response method named Removestar for the Remove Star button with the event type 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()
})
}
}
|
Running the app can now be added or deleted. Change the direction of the simulator or rotate the device to see how the app adjusts its interface. We built the app's user interface without adding a single line of constraints.
Note that the call to Removefromsuperview in Removestar (_:) is to remove subview from the view level. Call Removearrangedsubview Again (_:) just to tell stack view that no more constraints are needed to manage Subview. The subview will remain in the view hierarchy until it is called Removefromsuperview to remove it.
Conclusion
The Uistackview class greatly simplifies user interface development. This is good, especially with hardware changes. The use of Uistackview reduces the developer's tedious constraints on simple scenes, handing over the tedious work to Uikit.
If you are interested in any of the knowledge points in this article, you can download the complete project from GitHub.
Getting Started with IOS 9:uistackview