CHAPTER 4 EXERCISE SOLUTIONS

Answer to Question 1

mySecondViewController = [[MySecondViewController alloc]
                             initWithNibName:@“MySecondViewController”
                                   bundle:nil];

Answer to Question 2

- (void)viewDidLoad {
    //---create a CGRect for the positioning---
    CGRect frame = CGRectMake(20, 10, 280, 50);

    //---create a Label view---
    label = [[[UILabel alloc] initWithFrame:frame] autorelease];
    label.textAlignment = UITextAlignmentCenter;
    label.font = [UIFont fontWithName:@“Verdana” size:20];
    label.text = @“This is a label”;

    //---create a Button view---
    frame = CGRectMake(20, 60, 280, 50);
    button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = frame;
   [button setTitle:@“OK” forState:UIControlStateNormal];
   button.backgroundColor = [UlColor clearColor];

   //---add the views to the View window---
   [self.view addSubview:label];
   [self.view addSubview:button];
   [super viewDidLoad];
}

Answer to Question 3

//---add the action handler and set current class as target---
    [button addTarget:self
               action:@selector(buttonClicked:)
     forControlEvents:UIControlEventTouchUpInside];

    ...
    ...

-(IBAction) buttonClicked: (id) sender{
    //--add implementation here--
}

Answer to Question 4

In the HelloWorldViewController.m file, add the following code:

-(IBAction) buttonClicked: (id) sender{
    UIAlertView *alert =
        [[UIAlertView alloc] initWithTitle:@“Button Clicked!”
                                   message:@“Button was clicked!”
                                  delegate:self
                         cancelButtonTitle:@“OK”
                         otherButtonTitles:nil];
    [alert show];
    [alert release];
}

Get Beginning iOS 5 Application Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.