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

Home > Articles

iPhone User Interface Elements

In this chapter, you’ll look at the various views and controls available in iOS and examine how to use them.
This chapter is from the book

iOS 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 iOS 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 circle-a.jpg.

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 circle-b.jpg:
    myView.backgroundColor = [UIColor blueColor];
    [[self view] addSubview:myView];
    

    Code Listing 4.1 shows the completed code.

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 illustrates this circle-c.jpg: 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}.

listing_04_01.jpg

Code Listing 4.1 Creating a new view.

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 circle-d.jpg.

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 circle-e.jpg. 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.)

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.

listing_04_02.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.

listing_04_03.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 circle-f.jpg. 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.

    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 circle-g.jpg.

    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.

  3. You can visually set the autoresizingMask property in the size pane of the Inspector window in Interface Builder circle-h.jpg.

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.

listing_04_04.jpg

Code Listing 4.4 Using an autoresizing mask.

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 circle-i.jpg. Save the file as roundedCornerView.
  2. Open roundedCornerView.m, and modify your code to look like Code Listing 4.5.
  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.
  4. Build and run your application to see the result with rounded corners for the views circle-j.jpg.

    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.

  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];
    
    listing_04_05.jpg

    Code Listing 4.5 The roundedCornerView class.

  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);
    
listing_04_06.jpg

Code Listing 4.6 Replacing regular views with the custom class.

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 CGAffineTransform Concat() function.

    Code Listing 4.7 shows the completed code.

  2. Build and run your application circle-k.jpg.

    Your view should rotate and scale at the same time.

listing_04_07.jpg

Code Listing 4.7 Rotating and scaling the view.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020