Chapter 4. Exploring the Views

WHAT YOU WILL LEARN IN THIS CHAPTER

  • How to use the UIAlertView to display an alert view to the user

  • How to use the UIActionSheet to display some options to the user

  • How to use the UIPageControl to control paging

  • How to use the UIImageView to display images

  • How to use the UISegmentedControl to display a set of buttons for the user to choose among

  • How to use the UIWebView to display Web content in your application

  • How to add views dynamically to your application during runtime

  • How to wire a view to a View Controller

  • How to switch between views

Up to this point, you should already have some ideas of how to use Xcode and Interface Builder to build iPhone applications. In this chapter, you dive into the various views that you can use to spice up your applications. You learn how you can add views using Interface Builder, as well as how to create views dynamically during runtime.

USING THE VIEWS

So far, you have seen quite a number of views in action in the previous few chapters — Round Rect Button, TextField, and Label. All these views are quite straightforward, but they give you a good opportunity to understand how to apply the concepts behind outlets and actions.

To use more views, you can locate them from the Library window in Interface Builder (see Figure 4-1).

Figure 4-1

Figure 4.1. Figure 4-1

As you can see, the Library is divided into sections:

  • Controllers — contains views that control other views, such as the View Controller, Tab Bar Controller, Navigation Controller, and so on

  • Data Views — contains views that display data, such as the Image View, Table View, Data Picker, Picker View, and so on

  • Inputs and Values — contains views that accept inputs from users, such as the Label, Round Rect Button, Text Field, and so on

  • Windows, Views & Bars — contains views that display other, miscellaneous views, such as View, Search Bar, Toolbar, and so on

In the following sections, you learn how to use some of the views available in the Library. Although it is beyond the scope of this book to show the use of each view, you have the opportunity to see a number of views in action throughout the book. In this chapter, you learn some of the fundamental concepts of dealing with views so that you can use other views without problems.

Using the Alert View

One of the views that is not listed in the Library is the UIAlertView. The UIAlertView displays an alert view to the user and is usually created during runtime. Hence, to use it you have to create it using code.

Note

You have actually seen the UIAlertView in the previous chapter. In this section, you see how it actually works.

The UIAlertView is useful for cases in which you have to display a message to the user. In addition, it can serve as a quick debugging tool when you want to observe the value of a variable during runtime.

The following Try It Out explores the UIAlertView in more detail. You need to download the code as indicated here.

Note

Refer to Appendix D for a discussion of the concept of protocols in Objective-C.

Using the Action Sheet

Although the Alert view can display multiple buttons, its primary use is still as a tool to alert users when something happens. If you need to display a message with multiple choices for the user to select, you should use an action sheet rather than the Alert view. An action sheet displays a collection of buttons among which the user can select one. It always emerges from the bottom of the screen and is anchored to the sides of the screen, giving the cue to the user that the action sheet's details are connected to the current application. A good example of the use of an action sheet is when you tap on the "+" button in Safari. Tapping on the "+" button displays an action sheet where you add a bookmark, add the current page to the Home Screen, or mail the link of the current page. The following Try It Out puts you to work with an action sheet.

Page Control and Image View

On the Home screen of the iPhone, you see a series of dots at the bottom of the screen. A lighted dot represents the currently selected page. As you swipe the page to the next page, the next dot will be lighted. In the iPhone SDK, the series of dots is represented by the UIPageControl class. Figure 4-5 shows the page control in action on the Home screen of the iPhone.

Figure 4-5

Figure 4.5. Figure 4-5

In the following exercise, you learn how to use the page control view within your own application to switch between images displayed in the ImageView view.

Grouping Views Using the Segmented Control

A segmented control is a horizontal view that contains a series of buttons. Using a segmented control, users can tap any one of the buttons contained within it. Doing so deselects the button that was previously selected.

The following Try It Out shows how to use the segmented control to group several views together. It also shows how you can use this control to select a particular group of views.

Using the Web View

If you want to load Web pages from within your application, you can embed a Web browser in your application through the use of the UIWebView. Using the Web view, you can send a request to load Web content, which is a very useful if you want to convert an existing Web application into a native application (such as those written using Dashcode). All you need to do is to embed all the HTML pages into your Resources folder in your Xcode project and load the HTML pages into the Web view during runtime.

Note

Of course, depending on how complex your Web applications are, you may have to do some additional work to port your Web application to a native application if it involves server-side technologies such as CGI, PHP, or others.

The following Try It Out shows how to use the Web view to load a Web page.

ADDING VIEWS DYNAMICALLY USING CODE

Up to this point, all the UIs of your application have been created visually using Interface Builder. Although Interface Builder makes it relatively easy to build your UI using drag-and-drop, sometimes you are better off creating the UI using code. One such instance is when you need to create a dynamic UI, such as for games.

Note

I know of developers who swear by creating their UI using code. Interface Builder may be easy to use, but it can be confusing to some people. Because you often have more than one way of doing things in Interface Builder, it can create unnecessary complications.

In the following Try It Out, you learn how to create views dynamically from code, which will help you understand how views are constructed and manipulated.

UNDERSTANDING VIEW HIERARCHY

As views are created and added, they are added to a tree data structure. Views are displayed in the order that they are added. To verify this, modify the location of the UIButton object you created earlier by changing its location to CGRectMake(10, 30, 300, 50), as in the following:

//---create a Button view---
    frame = CGRectMake(10, 30, 300, 50);
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = frame;
    [button setTitle:@"Click Me, Please!" forState:UIControlStateNormal];
    button.backgroundColor = [UIColor clearColor];
    button.tag = 2000;
    [button addTarget:self action:@selector(buttonClicked:)
        forControlEvents:UIControlEventTouchUpInside];

When you now run the application again, you will notice that the button overlaps the label control (see Figure 4-19) since the button was added last:

Figure 4-19

Figure 4.19. Figure 4-19

[view addSubview:label];
    [view addSubview:button];

If you want to switch the order in which the views are displayed after they have been added, you can use the exchangeSubviewAtIndex:withSubviewAtIndex: method, like this:

[self.view addSubview:label];
    [self.view addSubview:button];

    [self.view exchangeSubviewAtIndex:1 withSubviewAtIndex:0];

    [button release];
    [label release];

The preceding statement in bold swaps the order of the Label and Button views. When the application is run again, the Label view will now appear on top of the Button view (See Figure 4-20).

Figure 4-20

Figure 4.20. Figure 4-20

To know the order of the various views already added, you can use the following code segment to print the value of the tag property for each view:

[self.view addSubview:label];
    [self.view addSubview:button];
    [self.view exchangeSubviewAtIndex:1 withSubviewAtIndex:0];

    for (int i=0; i<[self.view.subviews count]; ++i) {
        UIView *view = [self.view.subviews objectAtIndex:i];
        NSLog([NSString stringWithFormat:@"%d", view.tag]);
    }

The following method recursively prints out all the views contained in a UIView object:

-(void) printViews: (UIView *) view {
    if ([view.subviews count] > 0){
        for (int i=0; i<[view.subviews count]; ++i) {
            UIView *v = [view.subviews objectAtIndex:i];
            NSLog([NSString stringWithFormat:@"View index: %d Tag: %d",i, v.tag]);
            [self printViews:v];
        }
    } else
        return;
}

To remove a view from the current view hierarchy, use the removeFromSuperview method of the view you want to remove. For example, the following statement removes the label view:

[label removeFromSuperview];

SWITCHING VIEWS

When you create a View-based Application project in Xcode, you get a project with a single view with a corresponding View Controller. This is what you see when you edit the .xib file in Interface Builder. However, sometimes you need more than one view. For example, you may get the user to enter some information in one view and then based on the information that user entered, switch to another view for some actions.

The following Try It Out shows you how to switch between two views and how to wire a new view to a corresponding View Controller.

Animating the Transitions

In the previous section, you saw how to transition from one view to another. The transitioning happens very quickly and is not exciting visually. To live up to the high expectations expected by iPhone users, you need to add some animations to the transition. Fortunately, doing so is very easy using the APIs provided in the SDK, as the following Try It Out demonstrates.

Passing Data Between Views

Sometimes you need to pass data from one view to another. So how do you do that? The easiest way is to create a property on the target view and set the property on the calling view. The following Try It Out shows you how to do this.

SUMMARY

In this chapter, you have seen many views in action. You have also seen how views can be dynamically created during runtime. More important, you saw how to wire a view to a View Controller and how to switch between two views during runtime.

EXERCISES

  1. Describe the steps to connect a view to a View Controller.

  2. When do you use an Alert view and when do you use an action sheet?

  3. Create a UIButton from code and wire its Touch Up Inside event to an event handler.

  • WHAT YOU HAVE LEARNED IN THIS CHAPTER

TOPIC

KEY CONCEPTS

Using the UIAlertView

UIAlertView *alert = [[UIAlertView alloc]
    initWithTitle:@"Hello"
    message:@"This is an alert view"
    delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];

Handling events fired by UIAlertView

Ensure that your View Controller conforms to the UIAlertViewDelegate protocol.

Using the UIActionSheet

UIActionSheet *action =
    [[UIActionSheet alloc]
    initWithTitle:@"Title of Action Sheet"
    delegate:self
    cancelButtonTitle:@"OK"
    destructiveButtonTitle:
    @"Delete Message"
    otherButtonTitles:@"Option 1",
    @"Option 2", nil];

Handling events fired by UIActionSheet

Ensure that your View Controller conforms to the UIActionSheetDelegate protocol.

Wiring up the events for the UIPageControl

[pageControl addTarget:self
    action:@selector(pageTurning:)
    forControlEvents:UIControlEventValueChanged];

Using the UIImageView

[imageView1 setImage:
    [UIImage imageNamed:@"iMac_old.jpeg"]];

Wiring the events for the UISegmentedControl

[segmentedControl addTarget:self
    action:@selector(segmentChanged:)
    forControlEvents:UIControlEventValueChanged];

Using the UIWebView

NSURL *url =
    [NSURL URLWithString:@"http://www.apple.com"];
NSURLRequest *req =
   [NSURLRequest requestWithURL:url];
[webView loadRequest:req];

Animating during transitions

[UIView beginAnimations:@"flipping view"
    context:nil];
[UIView setAnimationDuration:1];
[UIView setAnimationCurve:
    UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:
    UIViewAnimationTransitionCurlDown
    forView:self.view cache:YES];

[self.view addSubview:
    secondViewController.view];

[UIView commitAnimations];

Passing data between views

Define a property in the receiving view and set its value in the calling view.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.179.239