Mobile Development

Working with Views

View objects are the main way your application interacts with the user. [1]


Before we dive in, let's build our vocabulary associated with UIViews:

  • UIView - The UIView class defines a rectangular area on the screen and the interfaces for managing the content in that area. At runtime, a view object handles the rendering of any content in its area and also handles any interactions with that content. [2]
  • Coordinate System - a system of defining the location of objects within a 2-dimensional space.
  • Frame - The frame rectangle for the view, measured in points. The origin of the frame is relative to the superview in which you plan to add it. [2]
  • Bounds - The bounds rectangle, which describes the view’s location and size in its own coordinate system. [2]
  • CGPoint - Represents a point in a two-dimensional coordinate system. [3]

    (x, y)

  • CGSize - A data structure that represents the dimensions of width and height. [3]

    (width, height)

  • CGRect - A data structure that represents the location and dimensions of a rectangle. [3]

    (x, y, width, height)

The difference between frame and bounds is the coordinate system the frame refers. As visualized below, frames refer to the parent view's coordinate system. Bounds refers to the view's own coordinate system:


Creating Views

The majority of time, you will be creating views within Interface Builder. They are automatically added to your view controllers, they are implicitly created with UIButtons and UILabels and of course, you can add them directly through the Object Library.

There may be times, however where it is important to create views within your code, outside of IB. The following code creates a simple view with a red background:

import UIKit

var view = UIView()
view.frame = CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0)
view.backgroundColor = UIColor.redColor()

The above codes output, as seen in Playgrounds:

Now that we've seen one view, let's see how views are displayed within a hierarchy.

View Hierarchy

An important concept of views is hierarchy. Views are layered on top of each other. In the below example, we see an UIView that contains an UIImageView, UITextView and a UIButton.

This hierarchy can be visualized using the Xcode Debug View Hierarchy:

Notice how each layer is either below, the same or above adjacent views. Planning your view hierarchy is crucial for good interface design.


[1] View Programming Guide for iOS -

[2] UIView Class Reference -

[3] CGGeometry Reference -

[4] View and Window Architecture -

[5] Debugging Views -