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

Home > Articles

This chapter is from the book

UIKit

UIKit contains all the objects necessary to build your UI. There are nearly a hundred separate classes defined in UIKit, so for the sake of brevity we’ll focus on those objects most common to user interfaces. They include

  • UILabel
  • UIImage and UIImageView
  • UIWebView
  • UIScrollView
  • UITableView and UITableViewCell
  • UINavigationBar
  • UITabBar

UILabel

You have already seen an example of UILabel in our “Hello, World!” app in the Part I iOS App Blueprint. A label is an interface object used to display text on the screen. The basic properties of a UILabel are outlined in Table 4.1.

Table 4.1 UILabel Properties and Descriptions

Property

Description

text

Static text displayed by the label

font

Font used to display the text of the label

textColor

Color of the text for the text label

textAlignment

Text alignment method used for the label. Options include UITextAlignmentLeft, UITextAlignmentRight, UITextAlignmentCenter

lineBreakMode

Line break method used for the label. Options include UILineBreakModeWordWrap, UILineBreakModeCharacterWrap, UILineBreakModeClip, UILineBreakModeHeadTruncation, UILineBreakModeTailTruncation, UILineBreakModeMiddleTruncation

numberOfLines

The maximum number of lines used to display the text. The default value for numberOfLines is one. Setting the numberOfLines to zero uses as many lines as necessary or possible within the bounds of the label

adjustsFontSizeToFitWidth

If set to YES, the label automatically scales the font size to fit the bounds of the label

minimumFontSize

If adjustsFontSizeToFitWidth is set to YES, this value is used for the lower limit when automatically adjusting the font size. If this limit is reached and the text label still does not fit, the content is truncated according to the lineBreakMode. If adjustsFontSizeToFitWidth is set to NO, this value is ignored

shadowColor

The color of the text shadow. By default, this color is set to nil

shadowOffset

The offset of the shadow for the text of the label. The shadow offset takes a CGSize structure that defines the (width, height) offset. The default offset is (0,-1) which means the shadow has a horizontal offset of zero and a vertical offset of -1. So, (0,-1) defines a one-pixel top shadow. Similarly, (0,1) would define a one-pixel bottom shadow

UILabel Example

1  CGRect frame = CGRectMake(0, 200, 320, 40);
2  UILabel *example = [[UILabel alloc] initWithFrame:frame];
3  example.text = @"Hello, World!";
4  example.textColor = [UIColor whiteColor];
5  example.shadowOffset = CGSizeMake(0, -1);
6  example.shadowColor = [UIColor darkGrayColor];
7  example.textAlignment = UITextAlignmentCenter;
8  example.backgroundColor = [UIColor lightGrayColor];

In this code sample, we set up a UILabel called example using a frame with a height of 40, a width of 320, and an origin of (0,200) in our superview. We then set the label text to “Hello, World!” in line 3, and the text color to white in line 4. In lines 5 and 6 we set up a text drop shadow. For a one-pixel top shadow, we define horizontal offset of 0, and a vertical offset of –1. Finally in line 7 we center the text within the bounds of the label by setting the textAlignment to UITextAlignmentCenter. Because the label’s width is the width of the iPhone screen, this centers the text on the screen.

Notice in line 8 that we set the background color of the label. Remember, because the UILabel is a subclass of UIView, the properties of the label are in addition to the properties that already exist in the UIView.

UIImage and UIImageView

Images can be powerful tools in iOS apps. The UIImage is a subclass of NSObject, and part of the Foundation framework. A simple object, the UIImage represents the data needed to display an image. The UIImage counterpart in UIKit is the UIImageView. UIImageView is a subclass of UIView, but it is designed for the purpose of drawing UIImages to the screen.

A UIImage supports the following formats:

  • Graphic Interchange Format (.gif)
  • Joint Photographic Experts Group (.jpg, .jpeg)
  • Portable Network Graphic (.png)
  • Tagged Image File Format (.tiff, .tif)
  • Windows Bitmap Format (.bmp, .BMPf)
  • Windows Icon Format (.ico)
  • Windows Cursor (.cur)
  • XWindow Bitmap (.xbm)

When creating a UIImageView, you have the option of initializing the view with the standard view initialization method, initWithFrame. However, because of the unique nature of images, iOS gives you an additional initialization method, initWithImage. When you initialize a UIImageView with an image, it automatically sets the height and width of the UIImageView to the height and width of the UIImage.

1  UIImage *myImage = [UIImage imageNamed:@"sample.png"];
2  UIImageView *myImageView = [[UIImageView alloc] initWithImage:myImage];
3  [self.view addSubview:myImageView];

In line 1, we create a UIImage from our sample image, sample.png. This UIImage is not really an image that can be displayed to the user; it is actually just a data type used to store the image data, similar to a string, array, or dictionary. In line 2, we create a UIImageView, which is a subclass of UIView and is designed to display the UIImage data type. After initializing myImageView with our image, we then add myImageView to the view hierarchy in line 3.

UIWebView

The UIWebView object is used to embed web-based content. You can choose to load a network request and pull content from the Internet, or you can use local resources from your app bundle and load an HTML formatted string. The UIWebView can also be used to display additional file types such as Excel (.xls), Keynote (.key.zip), Numbers (.numbers.zip), Pages (.pages.zip), PDF (.pdf), PowerPoint (.ppt), Rich Text Format (.rtf), and Word (.doc).

Table 4.2 Properties, Methods, and Descriptions

Property and Method

Description

delegate

The delegate is sent messages while the content is loading or when actions, such as selecting a link, are taken within the UIWebView

request

This parameter represents the NSURLRequest object of the web view’s loaded, or currently loading content. This value can only be set with the loadRequest: method

loading

Defined as a Boolean, YES or NO, this value indicates whether or not the UIWebView is finished loading the request

canGoBack

A Boolean value that defines whether or not the UIWebView can navigate backward. If YES, you must still implement a Back button that calls the method goBack:

canGoForward

A Boolean value that defines whether or not the UIWebView can navigate forward. If YES, you must still implement a Forward button that calls the method goForward:

dataDetectorTypes

Defines the behavior of the UIWebView when auto-detecting data types. Options include UIDataDetectorTypePhoneNumber, UIDataDetectorTypeLink, UIDataDetectorTypeAddress, UIDataDetectorTypeCalendarEvent, UIDataDetectorTypeNone, and UIDataDetectorTypeAll. If a data type detector is defined, iOS automatically converts detected data patterns into links that activate corresponding iOS functions. For example, phone numbers turn into links that, when tapped, prompt the user to initiate a phone call

UIWebView Example

Here we show a simple web browser implemented using UIWebView. The following code block creates a loading label and adds it to our window. You’ll notice that we set hidden to YES on our loading label. This means that even though the label is in the view hierarchy, it will not be visible.

1  CGRect frame = CGRectMake(0, 200, 320, 40);
2  myLoadingLabel = [[UILabel alloc] initWithFrame:frame];
3  myLoadingLabel.text = @"Loading...";
4  myLoadingLabel.textAlignment = UITextAlignmentCenter;
5  myLoadingLabel.hidden = YES;
6  [window addSubview:myLoadingLabel];
7
8  frame = CGRectMake(0, 20, 320, 460);
9  myWebView = [[UIWebView alloc] initWithFrame:frame];
10
11  NSURL *homeURL = [NSURL URLWithString:@"http://fromideatoapp.com"];
12  NSURLRequest *request = [[NSURLRequest alloc] initWithURL:homeURL];
13
14  myWebView setDelegate:self];
15  [myWebView loadRequest:request];
16  [request release];

Most of this code block should look familiar from our previous experience with UILabel. Lines 11 and 12 are used to create our request object. First we create an NSURL, then we allocate a new request variable using that URL. Once we have a request ready, all we need to do is apply it to our UIWebView, myWebView.

Before we can do that, however, we have to set up our UIWebView delegate. Here we are just setting it to self, which means myWebView will look to the current class to implement any delegate methods. In this case, we care about webViewDidStartLoad and webViewDidFinishLoad. These delegate methods are implemented in the next code block.

1  - (void)webViewDidStartLoad:(UIWebView *)webView{
2      myLoadingLabel.hidden = NO;
3      UIApplication *application = [UIApplication sharedApplication];
4      application.networkActivityIndicatorVisible = YES;
5  }
6
7  - (void)webViewDidFinishLoad:(UIWebView *)webView{
8      myLoadingLabel.hidden = YES;
9      UIApplication *application = [UIApplication sharedApplication];
10     application.networkActivityIndicatorVisible = NO;
11     [window addSubview:webView];
12 }

Lines 1 through 4 in this code block implement webViewDidStartLoad. When a UIWebView begins loading its request, it calls this method on its delegate. We’ll take advantage of this call by first making our loading label visible and turning on the device network activity indicator. Lines 6 through 10 implement webViewDidFinishLoad. Here, our UIWebView has finished loading its request and we want to add it to our window. In line 7 we hide the loading label, and in line 8 we hide the device network activity indicator. Finally, now that our UIWebView has finished loading the request, we add it as a subview to the main window.

UIScrollView

A UIScrollView is a special class used for displaying content that is larger than the bounds of the screen. If scrolling is enabled, this class automatically handles pinch-to-zoom and pan gestures using delegate methods to control content. Table 4.3 highlights some of the more unique properties of UIScrollView that we’ll cover in this chapter. If you go to fromideatoapp.com/reference#uiscrollview you can find a complete list of the properties from Apple’s developer documentation.

Table 4.3 UIScrollView Properties and Descriptions

Property

Description

delegate

The delegate called when UIScrollView encounters specific events

contentOffset

Defined as a CGPoint (x,y), this value is the offset of the origin of the contentView inside the UIScrollView

contentSize

The size of the contentView within the UIScrollView. The contentView is typically larger than the bounds of the UIScrollView, which allows the user to scroll and reveal hidden content

scrollEnabled

A Boolean value that enables or disables scrolling within the UIScrollView

directionalLockEnabled

Diagonal scrolling is permitted only when directionalLockEnabled is set to NO, which is the default value. When directional lock is enabled, at any given time a user is only able to scroll either vertically or horizontally, but not both at the same time. A user who starts scrolling vertically will be locked into a vertical scroll until dragging ends; the same would apply to horizontal scrolling

scrollsToTop

If scrollsToTop is set to YES, iOS automatically scrolls the UIScrollView to a contentOffset y value of 0 when the user double taps the iOS status bar. iOS will not scroll the x component of contentOffset

pagingEnabled

If pagingEnabled is set to YES, the UIScrollView will settle on contentOffset values that are multiples of the bounds of UIScrollView. The best example of this is actually the iPhone app launcher screen. All of the app icons exist in the same UIScrollView. When you swipe left or right, the UIScrollView settles on the nearest contentOffset that is a multiple of the width of the screen—this creates the pages

indicatorStyle

The bar style of the UIScrollView indicators. Options include UIScrollViewIndicatorStyleDefault, UIScrollViewIndicatorStyleBlack, and UIScrollViewIndicatorWhite

UIScrollView Example

The following example demonstrates a simple UIScrollView with paging enabled. You’ll notice that the behavior is similar to that of the iOS app launch screen. Lines 1 and 2 simply set up some constants used to create our scroll view demo. In line 4, we initialize a scrollView using our frame. Notice we set the bounds of the scrollView to a width of 320, or the width of an iPhone or iPod touch screen. In line 5, we set up our scrollView’s contentSize. For this example we want the contentSize, or the scrollable area, of the UIScrollView to be the width of the screen times the number of pages. Finally, we set pagingEnabled = YES, which tells the scrollView to settle on contentOffsets that are multiples of the bounds of our scrollView, or multiples of 320 along the horizontal axis.

Lines 8 through 27 look a little complicated, but let me break down what we’re doing. For each page of the scroll view, we want to create a UIView and add it as a subview to scrollView. To do this, the first thing we did was set up a for-loop to iterate through the number of pages defined in line 2. Because the origin of each “page” needs to be offset in the superview, we created a new frame with the x value 320 times our iteration variable. For page 0, this will evaluate to 0; for page 1, this will evaluate to 320. This pattern will continue through each page. Lines 11 through 21 simply create a UIView, set the background to an alternating white or light gray color, and then create a centered UILabel indicating the page number. Finally at the end of our loop, we add our view to scrollView and take care of some memory management.

1   CGRect frame = CGRectMake(0, 0, 320, 480);
2   int pageCount = 6;
3
4   UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:frame];
5   scrollView.contentSize = CGSizeMake(320*pageCount, 480);
6   scrollView.pagingEnabled = YES;
7
8   for (int i=0; i<pageCount; i++) {
9       CGRect f = CGRectMake(i*320, 0, 320, 480);
10      UIView *v = [[UIView alloc] initWithFrame:f];
11      if(i%2)
12        v.backgroundColor = [UIColor whiteColor];
13      else
14        v.backgroundColor = [UIColor lightGrayColor];
15
16      UILabel *l = [[UILabel alloc] initWithFrame:v.bounds];
17      l.text = [NSString stringWithFormat:@"View #%d",i+1];
18      l.backgroundColor = [UIColor clearColor];
19      l.textAlignment = UITextAlignmentCenter;
20      [v addSubview:l];
21      [scrollView addSubview:v];
22
23      [v release];
24      [l release];
25  }
26
27  [window addSubview:scrollView];

UITableView and UITableViewCell

UITableViews are among the most common UI objects used in iOS. UITableViews display content in the Mail app, SMS Chat, Settings, Safari History, and more. For the most part, any time you encounter content that scrolls vertically, it is accomplished with a UITableView. UITableView is a subclass of UIScrollView, but instead of defining the contentSize of the scrollView directly, you define the number of sections and rows within the UITableView and their heights, respectively. iOS automatically determines the appropriate size of the scrollView content.

With UITableViews come UITableViewCells. A UITableViewCell is a single row within the UITableView. Picture the iPhone’s default mail app. The UITableView represents the entire scrollView used to scroll through your mail messages. A UITableViewCell is used to represent each individual message.

Each UITableViewCell is a subview of the UITableView. However, instead of allocating a new UITableViewCell to represent each cell in memory, iOS will reuse cells so only a small number are allocated at a time. When a cell scrolls off the screen, it becomes available for reuse. As the screen scrolls a new cell into view, it retrieves cells that are available for reuse and repositions them in the superview. This means a table containing 100,000 cells would allocate as much memory to and have equal performance as a table containing only ten cells.

Because UITableViews are so common in iOS user interfaces, we will dedicate the entirety of Chapter 9, Creating Custom Table Views, to this topic.

UIToolbar

The UIToolbar is a common UI element used to present users with a set of options. UIToolbars are typically positioned at the bottom of the screen on iPhone apps, but they can be positioned almost anywhere in iPad workflows. The most common example of a UIToolbar is found in the Safari application.

In Safari for the iPhone, the blue toolbar at the bottom is a UIToolbar containing quick access to frequent actions such as navigate back, navigate forward, bookmark, history, and open pages. You will notice that when the iPhone rotates to portrait orientation, the toolbar icon automatically redistributes to fill the width of the UIToolbar.

Table 4.4 UIToolbar Properties and Descriptions

Property

Description

barStyle

iOS provides some default barStyle values for commonly used settings. Options include UIBarStyleDefault, UIBarStyleBlack, UIBarStyleBlackOpaque, and UIBarStyleTranslucent

tintColor

Setting the tintColor of UIToolbar colorizes the UIToolbar with any given color

translucent

A Boolean value that defines whether or not the UIToolbar is translucent

items

An array of UIBarButtonItems used to display in the UIToolbar. You can either choose from one of many system items or create your own custom UIBarButtonItem

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