Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beginning iOS5 Development.pdf
Скачиваний:
7
Добавлен:
09.05.2015
Размер:
15.6 Mб
Скачать

CHAPTER 4: More User Interface Fun

105

Implementing the Segmented Control Action

Save the nib file and single-click BIDViewController.m. Look for the toggleControls: method that Xcode created for us and add the following code to it:

-(IBAction)toggleControls:(id)sender {

//0 == switches index

if ([sender selectedSegmentIndex] == 0) { leftSwitch.hidden = NO; rightSwitch.hidden = NO; doSomethingButton.hidden = YES;

}

else {

leftSwitch.hidden = YES; rightSwitch.hidden = YES; doSomethingButton.hidden = NO;

}

}

This code looks at the selectedSegmentIndex property of sender, which tells us which of the sections is currently selected. The first section, called switches, has an index of 0, a fact that we’ve written down in a comment so that when we later revisit the code, we know what’s going on. Depending on which segment is selected, we hide or show the appropriate controls.

At this point, save and try running the application in the iOS simulator. If you’ve typed everything correctly, you should be able to switch between the button and the pair of switches using the segmented control, and if you tap either switch, the other one will change its value as well. The button, however, still doesn’t do anything. Before we implement it, we need to talk about action sheets and alerts.

Implementing the Action Sheet and Alert

Action sheets and alerts are both used to provide the user with feedback. as follows:

Action sheets are used to force the user to make a choice between two or more items. The action sheet comes up from the bottom of the screen and displays a series of buttons (see Figure 4–3). Users are unable to continue using the application until they have tapped one of the buttons. Action sheets are often used to confirm a potentially dangerous or irreversible action such as deleting an object.

Alerts appear as a blue, rounded rectangle in the middle of the screen (see Figure 4–4). Just like action sheets, alerts force users to respond before they are allowed to continue using the application. Alerts are usually used to inform the user that something important or out of the ordinary has occurred. Unlike action sheets, alerts may be presented with only a single button, although you have the option of presenting multiple buttons if more than one response is appropriate.

www.it-ebooks.info

106

CHAPTER 4: More User Interface Fun

NOTE: A view that forces users to make a choice before they are allowed to continue using their

application is known as a modal view.

Conforming to the Action Sheet Delegate Method

Remember back in Chapter 3 when we talked about the application delegate? Well, UIApplication is not the only class in Cocoa Touch that uses delegates. In fact, delegation is a common design pattern in Cocoa Touch. Action sheets and alerts both use delegates so that they know which object to notify when they’re dismissed. In our application, we’ll need to be notified when the action sheet is dismissed. We don’t need to know when the alert is dismissed, because we’re just using it to notify the user of something, not to actually solicit a choice.

In order for our controller class to act as the delegate for an action sheet, it needs to conform to a protocol called UIActionSheetDelegate. We do that by adding the name of the protocol in angle backets after the superclass in our class declaration. Add the following protocol declaration to BIDViewController.h:

#import <UIKit/UIKit.h>

@interface BIDViewController : UIViewController <UIActionSheetDelegate> @property (strong, nonatomic) IBOutlet UITextField *nameField; @property (strong, nonatomic) IBOutlet UITextField *numberField;

. . .

Showing the Action Sheet

Let’s switch over to BIDViewController.m and implement the button’s action method. We actually need to implement another method in addition to our existing action method: the UIActionSheetDelegate method that the action sheet will use to notify us that it has been dismissed.

First, look for the empty buttonPressed: method that Xcode created for you. Add the following code to that method to create and show the action sheet:

- (IBAction)buttonPressed:(id)sender {

UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Are you sure?"

delegate:self cancelButtonTitle:@"No Way!"

destructiveButtonTitle:@"Yes, I’m Sure!" otherButtonTitles:nil];

[actionSheet showInView:self.view];

}

Next, add a new method just after the existing buttonPressed: method:

www.it-ebooks.info

CHAPTER 4: More User Interface Fun

107

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex

{

if (buttonIndex != [actionSheet cancelButtonIndex])

{

NSString *msg = nil;

if (nameField.text.length > 0)

msg = [[NSString alloc] initWithFormat:

@"You can breathe easy, %@, everything went OK.", nameField.text];

else

msg = @"You can breathe easy, everything went OK.";

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Something was done" message:msg

delegate:self

cancelButtonTitle:@"Phew!"

otherButtonTitles:nil];

[alert show];

}

}

What exactly did we do there? Well, first, in the doSomething: action method, we allocated and initialized a UIActionSheet object, which is the object that represents an action sheet (in case you couldn’t puzzle that one out for yourself):

UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Are you sure?" delegate:self

cancelButtonTitle:@"No Way!" destructiveButtonTitle:@"Yes, I’m Sure!" otherButtonTitles:nil];

The initializer method takes a number of parameters. Let’s look at each of them in turn.

The first parameter is the title to be displayed. Refer back to Figure 4–3 to see how the title we’re supplying will be displayed at the top of the action sheet.

The next argument is the delegate for the action sheet. The action sheet’s delegate will be notified when a button on that sheet has been tapped. More specifically, the delegate’s actionSheet:didDismissWithButtonIndex: method will be called. By passing self as the delegate parameter, we ensure that our version of actionSheet:didDismissWithButtonIndex: will be called.

Next, we pass in the title for the button that users will tap to indicate they do not want to proceed. All action sheets should have a cancel button, though you can give it any title that is appropriate to your situation. You do not want to use an action sheet if there is no choice to be made. In situations where you want to notify the user without giving a choice of options, an alert view is more appropriate.

The next parameter is the destructive button, and you can think of this as the “yes, please go ahead” button, though once again, you can assign it any title.

www.it-ebooks.info

108

CHAPTER 4: More User Interface Fun

The last parameter allows you to specify any number of other buttons that you may want shown on the sheet. This final argument can take a variable number of values, which is one of the nice features of the Objective-C language. If we had wanted two more buttons on our action sheet, we could have done it like this:

UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Are you sure?"

delegate:self cancelButtonTitle:@"No Way!"

destructiveButtonTitle:@"Yes, I’m Sure!" otherButtonTitles:@"Foo", @"Bar", nil];

This code would have resulted in an action sheet with four buttons. You can pass as many arguments as you want in the otherButtonTitles parameter, as long as you pass nil as the last one. Of course, there is a practical limitation on how many buttons you can have, based on the amount of screen space available.

After we create the action sheet, we tell it to show itself:

[actionSheet showInView:self.view];

Action sheets always have a parent, which must be a view that is currently visible to the user. In our case, we want the view that we designed in Interface Builder to be the parent, so we use self.view. Note the use of Objective-C dot notation. self.view is equivalent to saying [self view], using the accessor to return the value of our view property.

Why didn’t we just use view, instead of self.view? view is a private instance variable of our parent class UIViewController, which means we can’t access it directly, but instead must use an accessor method.

Well, that wasn’t so hard, was it? In just a few lines of code, we showed an action sheet and required the user to make a decision. iOS will even animate the sheet for us without requiring us to do any additional work. Now, we just need to find out which button the user tapped. The other method that we just implemented, actionSheet:didDismissWithButtonIndex, is one of the UIActionSheetDelegate methods, and since we specified self as our action sheet’s delegate, this method will automatically be called by the action sheet when a button is tapped.

The argument buttonIndex will tell us which button was actually tapped. But how do we know which button index refers to the cancel button and which one refers to the destructive button? Fortunately, the delegate method receives a pointer to the UIActionSheet object that represents the sheet, and that action sheet object knows which button is the cancel button. We just need look at one of its properties, cancelButtonIndex:

if (buttonIndex != [actionSheet cancelButtonIndex])

This line of code makes sure the user didn’t tap the cancel button. Since we gave the user only two options, we know that if the cancel button wasn’t tapped, the destructive button must have been tapped, and it’s OK to proceed. Once we know the user didn’t cancel, the first thing we do is create a new string that will be displayed to the user. In a

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]