iOS Programming Cookbook
上QQ阅读APP看书,第一时间看更新

How it works...

First, we created the project with the Single View template; there are multiple templates that you can use or start with for your empty project. Then, we set the layout size of the view controller to a 4-inch size iPhone, as the project is intended to be for iPhone only, not iPad. This doesn't mean that your app will work on a 4-inch (iPhone 6 and iPhone 6s) iPhone only; it indicates what the layout will look like. We will see in later chapters how to design your app's UI, regardless of the screen size via size classes and auto layout.

Then, we saw how simple it is to add UIViews via interface builder. We added the red and blue views without wiring any line of code, and you can see how to change the view's properties in Attribute Inspector.

We add outlets to your views in the ViewController.swift file, which act as a reference to your components created in interface builder. So, you can access them any time in your code and do any specific action on them, such as hiding, resizing, translation, or adding subviews.

We then moved to source code to add two views, but programmatically. You first need to initialize the UIView and we used one of its initializers, which takes a frame to initialize with. The frame specifies the size and location (on superview) of the view. Then, we change the background color using one of its properties: .backgroundColor. I recommend opening the documentation of UIView, where you will see a list of properties and functions to be used.

Creating UIViews is nothing without presenting them onscreen, and to present it, you have to add a subview to any other view. The most common method used is addSubview(), which adds the view as a subview to the superview and on top of the view hierarchy. In some cases, adding on the top is not what you want, and you need some flexibility to choose where to add your view in the view hierarchy; that's why, UIView provides you with another three methods to insert a subview:

  • Function insertSubview(brownView, belowSubview: yellowView): This adds a subview below any other subview that you have in your view hierarchy. This method requires having a reference to the view you want to add below a subview.
  • Function insertSubview(view, atIndex: 2): This is a very flexible function to add any subview to your view hierarchy at any index. The index is 0 indexed, and 0 means the first subview.
  • Function insertSubview(view, aboveSubview: superview): This adds a subview above any other subview you have in your view hierarchy. This method requires having a reference to the view you want to add above a subview.

Using these methods, you have a full customization, where you can place your UIViews programmatically.