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

Home > Articles

  • Print
  • + Share This
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

  • + Share This
  • 🔖 Save To Your Account