How are UITableView cells made to be able to be deleted by users?
+1
A:
Take a look at the table view data source delegate method -tableView:commitEditingStyle:forRowAtIndexPath:
.
You override this method in your table view delegate (usually your table view controller) and put your deletion logic here.
For example, you can call a UIAlertView
to ask the user to confirm the deletion, or just manipulate the data model directly, removing the object from your table view's data source.
Alex Reynolds
2010-07-14 22:04:11
Thanks. If I want to remove an item at e.g. index 4 of an array, will the array need to be resorted or will it be done automatically?Regards
alJaree
2010-07-14 22:09:40
I'm trying to think of a case where you would need to resort after deleting an element of an array. Inserting, you may need to resort. Deleting, I'm not so sure.
Alex Reynolds
2010-07-14 22:11:25
Anyway, after changing your data source, you can call `[tableView reloadData]` or `[tableView deleteRowsAtIndexPaths:... withRowAnimation:...]` to tell the table view to refresh its presentation from the data source. It is preferable to use the second option as it requires less work, but the first option is handy if you want to test things out.
Alex Reynolds
2010-07-14 22:12:54
I don't know what shifting negative means for an array. In any case, take a look at the `NSMutableArray` method `-removeObjectAtIndex:`: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#jumpTo_16
Alex Reynolds
2010-07-14 22:17:43
Yeah :D i deleted the comment as I saw IWasRobbed answer included the removeObjectAtIndex method. thanks.
alJaree
2010-07-14 22:35:12
+2
A:
A quick example would be:
// create a mutable array to manage your table data
NSMutableArray *tableList;
@property (nonatomic, retain) NSMutableArray *tableList;
in your viewDidLoad
method you can initialize it with data (you should check if tableList
is nil first though)
NSString *path = [[NSBundle mainBundle] pathForResource:@"TableData" ofType:@"plist"];
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path];
self.tableList = array;
[array release];
then in the implementation file, you implement this delegate method
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = [indexPath row];
[self.tableList removeObjectAtIndex:row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
you can then toggle editing mode via
[self.tableView setEditing:!self.tableView.editing animated:YES];
iWasRobbed
2010-07-14 22:12:57
I had the arrays setup already. Implemented the delegate method. This worked perfectly. Thanks a lot.
alJaree
2010-07-15 09:04:17