Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Apple > iPhone

iPhone SDK 3 User Interface Elements

  • Print
  • + Share This
  • 💬 Discuss
This chapter is from the book
Do you want to create your own iPhone app? Get started with this lesson on user interface elements in the iPhone SDK 3, including views and controls.

The iPhone SDK offers a rich set of buttons, sliders, switches, and other user interface elements for you to use in creating your applications. These elements can be roughly divided into two main groups, views and controls.

Views provide the primary canvas and drawing functionality of your user interface. They also give your application the ability to handle touch events.

Controls extend upon this functionality and provide a way for users to interact with your application by defining what is known as the target-action mechanism: the ability for a control to send an action (method call) to a target (object) when an event (touch) occurs.

In this chapter, you'll look at the various views and controls available in the iPhone SDK and examine how to use them.

All the examples use the view-based Application template, with the code running in the view controller.

Views

A view is the common name given to instances of UIView. You can think of a view as your application's canvas; in other words, if you are adding UI elements to your iPhone's interface, you are adding them to a view. All the UI elements discussed in this chapter are themselves subclasses of UIView and so inherit its properties and behavior.

The root level of your iPhone application interface consists of a single UIWindow to which you would typically add one or more views to work with, instead of using UIWindow directly.

Since UIView is a subclass of UIResponder, it can receive touch events. For most views, you'll receive only a single-touch event unless you set the multipleTouchEnabled property to TRUE. You can determine whether a view can receive touch events by modifying its userInteractionEnabled property. You can also force a view to be the only view to receive touch events by setting the exclusiveTouch property to YES. (For more information on working with touch events, see Chapter 7, "Touches, Shakes, and Orientation.")

You can also nest views within each other in what's known as the view hierarchy. Child views are known as subviews, and a view's parent is its superview.

Frames

Views are represented by a rectangular region of the screen called a frame. The frame specifies the origin (x, y) and size (width, height) of the view, in relation to its parent superview. The origin of the coordinate system for all views is the upper-left corner of the screen (Figure 4.1).

Figure 4.1

Figure 4.1 Child views (subviews) are nested inside their parent view (superview). A view's origin is at the top-left corner.

To add a view to your application:

  1. Create a CGRect to represent the frame of the view, and pass it as the first parameter of the view's initWithFrame: method:

    CGRect viewFrame = CGRectMake(10,10,100,100);
    UIView *myView = [[UIView alloc] initWithFrame:viewFrame];
    

    Here you are creating a view that is inset 10 pixels from the top left of its superview and that has a width and height of 100 pixels.

  2. Since the view is transparent by default, set its background color before adding it to the view controller's existing view (Figure 4.2):
    myView.backgroundColor = [UIColor blueColor];
    [[self view] addSubview:myView];
    Figure 4.2

    Figure 4.2 Adding a subview to the view controller's main view.

    Code Listing 4.1 shows the completed code.
    figure_04_02a.jpg

    Code Listing 4.1 Creating a new view.

Bounds

A view's bounds are similar to its frame, but the location and size are relative to the view's own coordinate system rather than those of its superview. In the previous example, the frame's origin is {10,10}, but the origin of its bounds is {0,0}. (The width and height for both the frame and the bounds are the same.)

The console output in Figure 4.3 illustrates this: After moving the view 25 pixels in the x direction (using the view's center property), the frame origin is now {35,10}, whereas the bounds origin remains at {0,0}.

Figure 4.3

Figure 4.3 Console output after moving the view. Notice that although the frame changes, the bounds remain the same.

Let's say you want to create a view so that it completely fills its superview. A common mistake is to use the frame of the superview.

If you tried to run this code in your application, you'd see a gap at the top of the subview (Figure 4.4).

Figure 4.4

Figure 4.4 Setting the frame incorrectly by using the frame of the superview. Notice the gap at the top.

Recall that, in the project, the UIWindow is at the top level. The UIWindow has two subviews: the status bar and the main view 20 pixels below (Figure 4.5). The origin of the frame of the main view is actually {0,20}. (Remember, a view's frame is in relation to its superview's coordinate system.)

Figure 4.5

Figure 4.5 The enclosing UIWindow contains both the status bar and the view controller's view as subviews. Notice how the controller's view has an origin starting at {0,20} for its frame.

The solution to this problem is to use the bounds of the superview (Code Listing 4.2), which causes the view to correctly fill its superview.

figure_04_05a.jpg

Code Listing 4.2 Initializing the view's frame with its superview's bounds.

Animation

Many properties of a view can be animated, including its frame, bounds, backgroundColor, alpha level, and more. You'll now look at some simple examples that illustrate additional view concepts.

To animate your view:

  1. Retrieve the center of the view controller's main view:
    CGPoint frameCenter = self.view.center;
  2. Create a view, set its background color, and, just as you did earlier, add it to the main view:

    float width  = 50.0;
    float height = 50.0;
    CGRect viewFrame = CGRectMake(frameCenter.x-width, frameCenter.y-height,width*2, height*2);
    UIView *myView = [[UIView alloc] initWithFrame:viewFrame];
    myView.backgroundColor = [UIColor blueColor];
    [[self view] addSubview:myView];
    

    Here you are positioning your view in the center of its superview and giving it a width and height of 50 pixels.

  3. Set up an animation block:

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:1.0];
    

    An animation block is a wrapper around a set of changes to animatable properties. In this example, the animation lasts for one second.

  4. Resize the view:

    viewFrame = CGRectInset(viewFrame, -width, -height);
    [myView setFrame:viewFrame];

    The CGRectInset() function takes a source rectangle and then creates a smaller or larger rectangle with the same center point. In this example, a negative value for the width and height creates a larger rectangle.

  5. Close the animation block:

    [UIView commitAnimations];

    This will cause all of the settings within the animation block to be applied.

  6. Build and run the application.

    You should see the view grow in size over a period of one second. Code Listing 4.3 shows the completed code.

    figure_04_05b.jpg

    Code Listing 4.3 Animating a view.

Autosizing

When a view changes size or position, you often want any subviews contained within the view to change size or position in proportion to their containing superview. You can accomplish this by using a view's autoresizing mask. Now let's add a second subview inside the view you created in the previous exercise.

To add a subview:

  1. Create a CGRect for the subview's frame, again using the shortcut CGRectInset() function:

    CGRect subViewFrame = CGRectInset(myView.bounds,width/2.0,height/2.0);
    UIView *mySubview = [[UIView alloc] initWithFrame:subViewFrame];
    mySubview.backgroundColor = [UIColor yellowColor];
    [myView addSubview:mySubview];
    

    This time, the positive width and height values for the CGRectInset function make the new view smaller. To make them stand out, give it a different background color.

  2. Build and run the application (Figure 4.6). The new subview starts off in the center of its superview, but then it remains "pinned" to its initial location as the animation progresses and ends up in the top-left corner.

    Figure 4.6

    Figure 4.6 Animating multiple views without using an autoresizing mask. Notice how the new subview ends up in the top-left corner of its superview.

    Code Listing 4.4 shows this code updated to use an autoresizing mask. Notice how you set all four margins of the subview using the bitwise OR operator (the | symbol) between the constant values (Table 4.1). Notice also that even though the animation is specified on the superview, the subview still animates automatically. Figure 4.7 shows the effect of using this mask.

    figure_04_08a.jpg

    Code Listing 4.4 Using an autoresizing mask.

    Table 4.1. Available autoresizingMask values

    VALUE

    DESCRIPTION

    UIViewAutoresizingNone

    The view does not resize.

    UIViewAutoresizingFlexibleLeftMargin

    The view resizes by expanding or shrinking in the direction of the left margin.

    UIViewAutoresizingFlexibleWidth

    The view resizes by expanding or shrinking its width.

    UIViewAutoresizingFlexibleRightMargin

    The view resizes by expanding or shrinking in the direction of the right margin.

    UIViewAutoresizingFlexibleTopMargin

    The view resizes by expanding or shrinking in the direction of the top margin.

    UIViewAutoresizingFlexibleHeight

    The view resizes by expanding or shrinking its height.

    UIViewAutoresizingFlexibleBottomMargin

    The view resizes by expanding or shrinking in the direction of the bottom margin.

    Figure 4.7

    Figure 4.7 Using the autoresizing mask property, the subview remains in the center of its superview during an animation.

  3. You can visually set the autoresizingMask property in the size pane of the Inspector window in Interface Builder (Figure 4.8).
    Figure 4.8

    Figure 4.8 Setting the autoresizing mask in Interface Builder.

Custom drawing

By default, the visual representation of a UIView is fairly boring. You can manipulate the size, background color, and alpha levels of the view, but not much else.

Luckily, it's relatively simple to create your own UIView subclasses where you can implement custom drawing behavior. To see how this might be done, you'll now learn how to create a UIView subclass with rounded corners.

To create a custom rounded-corner view:

  1. In Xcode, select File > New File. Create a new Objective-C class, making sure that "Subclass of" is set to UIView (Figure 4.9). Save the file as roundedCornerView.
    Figure 4.9

    Figure 4.9 Adding a custom class to draw the rounded corner view.

  2. Open roundedCornerView.m, and modify your code to look like Code Listing 4.5.
    figure_04_10a.jpg

    Code Listing 4.5 The roundedCornerView class.

  3. Open UITestViewController.m, and replace all instances of UIView with roundedCornerView. Don't forget to also import the header file for roundedCornerView.h at the top of the file. Code Listing 4.6 shows the updated code.
    figure_04_10b.jpg

    Code Listing 4.6 Replacing regular views with the custom class.

  4. Build and run your application.

    Figure 4.10 shows the application with rounded corners for the views. As you can see, custom drawing happens in the drawRect: method of roundedCornerView. You set a couple of variables here—one to determine the width of the line you will be drawing and another to determine the color.

    Figure 4.10

    Figure 4.10 In the updated application, the views now have rounded corners.

  5. By setting the color to the superview's background color, you are essentially "erasing" any time you draw in the subview.
    float lineWidth = 10.0;
    UIColor *parentColor = [[self superview] backgroundColor];
    
  6. Now you get a reference to the current graphics context and set the pen color and width.

    A graphics context is a special type that represents the current drawing destination, in this case the custom view's contents.

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(ctx, parentColor.CGColor);
    CGContextSetLineWidth(ctx, lineWidth);
    
  7. Finally, call a custom function that draws a line around the outside of the view, rounding at each corner:
    CGContextStrokeCorners(ctx,rect);

Transforms

You've already looked at resizing a view by increasing the width and height of its frame. Another way to perform the same task is by using a transform.

A transform maps the coordinates system of a view from one set of points to another. Transformations are applied to the bounds of a view. In addition to scaling, you can also rotate and move a view using transforms.

To resize your view using a scale transform:

  • Add the following code to your application:

    CGAffineTransform scale = CGAffineTransformMakeScale(2.0,2.0);
    myView.transform = scale;
    

    This creates a scale transform, doubling both the width and the height of your view.

    or

    Transforms can also be used to move views by using a translate transform:

    CGAffineTransform translate = CGAffineTransformMakeTranslation(50,50);
    myView.transform = translate;
    

    This would cause a view to move by 50 pixels along both the x- and y-axes.

    or

    Finally, you can apply a rotation transform to rotate your views:

    CGAffineTransform rotate = CGAffineTransformMakeRotation(radiansForDegrees(180));
    myView.transform = rotate;
    

    Because rotations are specified in radians, you use a function to convert from degrees.

To apply both a rotation transform and a scale transform to your view:

  1. Update the code to look like the following:

    CGAffineTransform scale = CGAffineTransformMakeScale(2.0,2.0);
    CGAffineTransform rotate = CGAffineTransformMakeRotation(radiansForDegrees(180));
    CGAffineTransform myTransform = CGAffineTransformConcat(scale,rotate);
    myView.transform = myTransform;
    

    Note how you can combine transformations using the CGAffineTransformConcat() function.

    Code Listing 4.7 shows the completed code.

    figure_04_10c.jpg

    Code Listing 4.7 Rotating and scaling the view.

  2. Build and run your application (Figure 4.11).

    Figure 4.11

    Figure 4.11 The view both rotating and scaling.

    Your view should rotate and scale at the same time.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus