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

CHAPTER 9: Navigation Controllers and Table Views

317

Figure 9–17. The table with buttons in the accessory view

Tapping a row anywhere but on its switch will display an alert telling you whether the switch for that row is turned on or off.

At this point, you should be getting pretty comfortable with how this all works, so let’s try a slightly more difficult case, shall we? Next, we’ll take a look at how to allow the user to reorder the rows in a table.

NOTE: How are you doing? Hanging in there? We know this chapter is a bit of a marathon, with a lot of stuff to absorb. At this point, you’ve already accomplished a lot. Why not take a break, and

grab a Fresca and a pastel de Belém? We’ll do the same. Come back when you’re refreshed and

ready to move on.

Fourth Subcontroller: Movable Rows

Moving and deleting rows, as well as inserting rows at a specific spot in the table, are tasks that can be implemented fairly easily. All three are implemented by turning on something called editing mode, which is done using the setEditing:animated: method on the table view.

www.it-ebooks.info

318

CHAPTER 9: Navigation Controllers and Table Views

The setEditing:animated: method takes two Boolean values. The first indicates whether you are turning on or off editing mode, and the second indicates whether the table should animate the transition. If you set editing to the mode it’s already in (in other words, turning it on when it’s already on or off when it’s already off), the transition will not be animated, regardless of what you specify in the second parameter.

Once editing mode is turned on, a number of new delegate methods come into play. The table view uses them to ask if a certain row can be moved or edited, and again to notify you if the user actually does move or edit a specific row. It sounds more complex than it is. Let’s see it in action in our movable row controller.

Because we don’t need to display a detail view, this view controller can be implemented without a nib and with just a single controller class. Select the Nav folder in the project navigator in Xcode, and then press N or select File New New File…. Select Cocoa Touch, select Objective-C class, and click Next. Then enter BIDMoveMeController as the class name, and enter BIDSecondLevelViewController in the Subclass of control. Click

Next again, and save the class files as usual.

Creating the Movable Row View

In our header file, we need two things. First, we need a mutable array to hold our data and keep track of the order of the rows. It must be mutable because we need to be able to move items around as we are notified of moves. We also need an action method to toggle edit mode on and off. The action method will be called by a navigation bar button that we will create.

Single-click BIDMoveMeController.h, and make the following changes:

#import "BIDSecondLevelViewController.h"

@interface BIDMoveMeController : BIDSecondLevelViewController

@property (strong, nonatomic) NSMutableArray *list; - (IBAction)toggleMove;

@end

Now, switch over to BIDMoveMeController.m, and add the following code:

#import "BIDMoveMeController.h"

@implementation BIDMoveMeController

@synthesize list;

- (IBAction)toggleMove {

[self.tableView setEditing:!self.tableView.editing animated:YES];

if (self.tableView.editing) [self.navigationItem.rightBarButtonItem setTitle:@"Done"];

else

[self.navigationItem.rightBarButtonItem setTitle:@"Move"];

}

www.it-ebooks.info

CHAPTER 9: Navigation Controllers and Table Views

319

- (void)viewDidLoad { [super viewDidLoad]; if (list == nil) {

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects: @"Eeny", @"Meeny", @"Miney", @"Moe", @"Catch", @"A", @"Tiger", @"By", @"The", @"Toe", nil];

self.list = array;

}

UIBarButtonItem *moveButton = [[UIBarButtonItem alloc] initWithTitle:@"Move" style:UIBarButtonItemStyleBordered target:self action:@selector(toggleMove)];

self.navigationItem.rightBarButtonItem = moveButton;

}

#pragma mark -

#pragma mark Table Data Source Methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

return [list count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *MoveMeCellIdentifier = @"MoveMeCellIdentifier"; UITableViewCell *cell = [tableView

dequeueReusableCellWithIdentifier:MoveMeCellIdentifier]; if (cell == nil) {

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MoveMeCellIdentifier];

cell.showsReorderControl = YES;

}

NSUInteger row = [indexPath row]; cell.textLabel.text = [list objectAtIndex:row];

return cell;

}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {

return UITableViewCellEditingStyleNone;

}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {

return YES;

}

- (void)tableView:(UITableView *)tableView

www.it-ebooks.info

320

CHAPTER 9: Navigation Controllers and Table Views

moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { NSUInteger fromRow = [fromIndexPath row]; NSUInteger toRow = [toIndexPath row];

id object = [list objectAtIndex:fromRow]; [list removeObjectAtIndex:fromRow];

[list insertObject:object atIndex:toRow];

}

@end

Let’s take this one step at a time. The first code we added is the implementation of our action method.

- (IBAction)toggleMove {

[self.tableView setEditing:!self.tableView.editing animated:YES];

if (self.tableView.editing) [self.navigationItem.rightBarButtonItem setTitle:@"Done"];

else

[self.navigationItem.rightBarButtonItem setTitle:@"Move"];

}

All that we’re doing here is toggling edit mode and then setting the button’s title to an appropriate value. Easy enough, right?

The next method we touched is viewDidLoad. The first part of that method doesn’t do anything you haven’t seen before. It checks to see if list is nil, and if it is (meaning this is the first time this method has been called), it creates a mutable array filled with values, so our table has some data to show. After that, though, there is something new.

UIBarButtonItem *moveButton = [[UIBarButtonItem alloc] initWithTitle:@"Move" style:UIBarButtonItemStyleBordered target:self

action:@selector(toggleMove)]; self.navigationItem.rightBarButtonItem = moveButton;

Here, we’re creating a button bar item, which is a button that will sit on the navigation bar. We give it a title of Move and specify a constant, UIBarButtonItemStyleBordered, to indicate that we want a standard bordered bar button. The last two arguments, target and action, tell the button what to do when it is tapped. By passing self as the target and giving it a selector to the toggleMove method as the action, we are telling the button to call our toggleMove method whenever the button is tapped. As a result, any time the user taps this button, editing mode will be toggled. After we create the button, we add it to the right side of the navigation bar, and then release it.

Unlike most view controllers we create, this one does not have a viewDidUnload method. That’s intentional. We have no outlets, and if we were to flush our list array, we would lose any reordering that the user had done when the view is flushed, which we don’t want to happen. Therefore, since we have nothing to do in the viewDidUnload method, we don’t bother to override it.

www.it-ebooks.info

CHAPTER 9: Navigation Controllers and Table Views

321

Now, skip down to the tableView:cellForRowAtIndexPath: method we just added. Did you notice the following new line of code?

cell.showsReorderControl = YES;

Standard accessory icons can be specified by setting the accessoryType property of the cell. But the reorder control is not a standard accessory icon. It’s a special case that’s shown only when the table is in edit mode. To enable the reorder control, we need to set a property on the cell itself. Note, though, that setting this property to YES doesn’t actually display the reorder control until the table is put into edit mode. Everything else in this method is stuff we’ve done before.

The next new method is short but important. In our table view, we want to be able to reorder the rows, but we don’t want the user to be able to delete or insert rows. As a result, we implement the method tableView:editingStyleForRowAtIndexPath:. This method allows the table view to ask if a specific row can be deleted or if a new row can be inserted at a specific spot. By returning UITableViewCellEditingStyleNone for each row, we are indicating that we don’t support inserts or deletes for any row.

Next comes the method tableView:canMoveRowAtIndexPath:. This method is called for each row, and it gives you the chance to disallow the movement of specific rows. If you return NO from this method for any row, the reorder control will not be shown for that row, and the user will be unable to move it from its current position. We want to allow full reordering, so we just return YES for every row.

The last method, tableView:moveRowAtIndexPath:fromIndexPath:, is the one that will actually be called when the user moves a row. The two parameters besides tableView are both NSIndexPath instances that identify the row that was moved and the row’s new position. The table view has already moved the rows in the table, so the user is seeing the correct display, but we need to update our data model to keep the two in sync and avoid causing display problems.

First, we retrieve the row that needs to be moved. Then we retrieve the row’s new position.

NSUInteger fromRow = [fromIndexPath row];

NSUInteger toRow = [toIndexPath row];

We now need to remove the specified object from the array and reinsert it at its new location.

id object = [list objectAtIndex:fromRow]; [list removeObjectAtIndex:fromRow];

After we’ve removed it, we need to reinsert it into the specified new location.

[list insertObject:object atIndex:toRow];

Well, there you have it. We’ve implemented a table that allows reordering of rows.

www.it-ebooks.info

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