iPhone SDK Tutorial – {Part 5}: Add, Delete & Reorder UITableView Rows

Introduction:

I am going to write series of UITableView tutorials (Video Tutorials as well). My target is to make the customized UITableView using UITableViewCell which is requested on “Request Tutorial” page. Following are the list of tutorials, which I will be posting on this blog:

1. Create a Simple UITableView [Populate UITableView With Array]
2. Navigatation in UITableView [Navigatation on UITableView using didSelectRowAtIndexPath]
3. Grouped UITableView [Using Interface builder]
4. Tips for UITableView Design [Change UITableView properties i.e background colour, accessory type, add footer and header]
5. Add, Delete & Re-order UITableView rows
6. Creating UITableView using UITableViewCell
7. Adding Pictures into your UITableView using Interface builder
8. UITableView & UITableViewCell examples and tips

[Note: If you want more tutorials on UITableView or UITableViewCell, then add a comment on "Request Tutorial" Page]

Idea of this tutorial:

This tutorial will explain, how you can change the UITableView data. I will add, delete and re-order rows in UITableView.
Out put of this tutorial will look like this

Picture 2 iPhone SDK Tutorial   {Part 5}: Add, Delete & Reorder UITableView Rows
Table View in Edit mode

Picture 3 iPhone SDK Tutorial   {Part 5}: Add, Delete & Reorder UITableView Rows
Reorder rows inside UITableView
Picture 4 iPhone SDK Tutorial   {Part 5}: Add, Delete & Reorder UITableView Rows
Delete rows from table view

Steps to follow

Follow these steps to achieve the output like above:

Step 1: Open the SimpleTable project in Xcode (you can grab this code from here. [Note: I am using UITableView Tutorial part 2 code here]). In SimpleTableViewController.m file, change viewDidLoad method by adding the following code:

UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@"Add" style:UIBarButtonItemStyleBordered target:self action:@selector(AddButtonAction:)];
[self.navigationItem setRightBarButtonItem:addButton];
UIBarButtonItem *deleteButton = [[UIBarButtonItem alloc] initWithTitle:@"Delete" style:UIBarButtonItemStyleBordered target:self action:@selector(DeleteButtonAction:)];
[self.navigationItem setLeftBarButtonItem:deleteButton];
[addButton release];
[deleteButton release];

Step 2: Add these two method at the end of this class

- (IBAction)AddButtonAction:(id)sender{
[arryData addObject:@"Mac Mini"];
[tblSimpleTable reloadData];
}

- (IBAction)DeleteButtonAction:(id)sender{
[arryData removeLastObject];
[tblSimpleTable reloadData];
}

Step 3: Open SimpleTableViewController.h file and add these two methods definition:

- (IBAction)AddButtonAction:(id)sender;
- (IBAction)DeleteButtonAction:(id)sender;

Step 4: Run your application and click on ‘add’ & ‘delete’ buttons. This is just a simple Test. Now remove all the code we added above [Move back to starting point (or grab the code from here)].

Picture 5 iPhone SDK Tutorial   {Part 5}: Add, Delete & Reorder UITableView Rows
Test Table Add Delete Row

Step 5: Add the following method definition in SimpleTableViewController.h file:

- (IBAction) EditTable:(id)sender;

Step 6: Now add following code in viewDidLoad method inside SimpleTableViewController.m file:

UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(EditTable:)];
[self.navigationItem setLeftBarButtonItem:addButton];

Step 7: Now add the method body in the class as:

- (IBAction) EditTable:(id)sender{
if(self.editing)
{
[super setEditing:NO animated:NO];
[tblSimpleTable setEditing:NO animated:NO];
[tblSimpleTable reloadData];
[self.navigationItem.leftBarButtonItem setTitle:@"Edit"];
[self.navigationItem.leftBarButtonItem setStyle:UIBarButtonItemStylePlain];
}
else
{
[super setEditing:YES animated:YES];
[tblSimpleTable setEditing:YES animated:YES];
[tblSimpleTable reloadData];
[self.navigationItem.leftBarButtonItem setTitle:@"Done"];
[self.navigationItem.leftBarButtonItem setStyle:UIBarButtonItemStyleDone];
}
}

Step 8: Run the application and click on ‘Edit’ and ‘Done’ buttons. You will see that only ‘-’ icons are added to the left of cells.

Picture 6 iPhone SDK Tutorial   {Part 5}: Add, Delete & Reorder UITableView Rows
Delete Icon in Table View

Step 9: We want to add ‘-’ icons to all the rows but also want to have a ‘+’ icons as well. So for that we want to have one more row in your table. To implement that, you have to change in numberOfRowsInSection & cellForRowAtIndexPath methods. So both method will look like this:

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
int count = [arryData count];
if(self.editing) count++;
return count;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
cell.hidesAccessoryWhenEditing = YES;
}
int count = 0;
if(self.editing && indexPath.row != 0)
count = 1;
// Set up the cell...
if(indexPath.row == ([arryData count]) && self.editing){
cell.text = @"add new row";
return cell;
}

cell.text = [arryData objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}

Step 10: Run the application and you will see a new row inserted in UITableView (add new row). But left to that row is also a delete icon.

Picture 7 iPhone SDK Tutorial   {Part 5}: Add, Delete & Reorder UITableView Rows
Adding a row in UITableView

To change it, you have to write a new method inside your class which is editingStyleForRowAtIndexPath:

// The editing style for a row is the kind of button displayed to the left of the cell when in editing mode.
- (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
// No editing style if not editing or the index path is nil.
if (self.editing == NO || !indexPath) return UITableViewCellEditingStyleNone;
// Determine the editing style based on whether the cell is a placeholder for adding content or already
// existing content. Existing content can be deleted.
if (self.editing && indexPath.row == ([arryData count])) {
return UITableViewCellEditingStyleInsert;
} else {
return UITableViewCellEditingStyleDelete;
}
return UITableViewCellEditingStyleNone;
}

Step 11: Run the application and it will show you a ‘+’ icon with ‘add new row’. If you click on ‘delete’ icon or ‘+’ icon, you will see nothing change inside your application.

Picture 8 iPhone SDK Tutorial   {Part 5}: Add, Delete & Reorder UITableView Rows
Insert and Delete icons in UITableView

For that you have to write a commitEdittingStyle method inside your class:

// Update the data model according to edit actions delete or insert.
- (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {
[arryData removeObjectAtIndex:indexPath.row];
[tblSimpleTable reloadData];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
[arryData insertObject:@"Mac Mini" atIndex:[arryData count]];
[tblSimpleTable reloadData];
}
}

Step 12: Run your application and click on ‘+’ and ‘-’ icons.

Picture 9 iPhone SDK Tutorial   {Part 5}: Add, Delete & Reorder UITableView Rows
Working add & delete rows in UITableView

This is working fine but one part of this tutorial is still remaining which is ‘re-ordering’ of table rows. For that you have to add two methods inside your class, canMoveRowAtIndexPath & moveRowAtIndexPath:

#pragma mark Row reordering
// Determine whether a given row is eligible for reordering or not.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
// Process the row move. This means updating the data model to correct the item indices.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
toIndexPath:(NSIndexPath *)toIndexPath {
NSString *item = [[arryData objectAtIndex:fromIndexPath.row] retain];
[arryData removeObject:item];
[arryData insertObject:item atIndex:toIndexPath.row];
[item release];
}

Run the application and you will see the final output.

Picture 10 iPhone SDK Tutorial   {Part 5}: Add, Delete & Reorder UITableView Rows
Add, Delete & Re-order UITableView

You can grab this code from here.

Now watch me doing it.

Popularity: 58% [?]

My name is Adeem M Basraa. I am a software engineer from Lahore, PK. I’ve been involved in software development for nearly 4 years, with the last 1 year focused on application development for mobile devices (iPhone & Android).

22 Comments on "iPhone SDK Tutorial – {Part 5}: Add, Delete & Reorder UITableView Rows"

  1. Eddy says:

    Hi Adeem,

    Thank you for this tutorial! It was very helpful. I have an unusual requirement in my app which I would like to have reordering of rows only. Do you know how I can hide the add/delete part if the tableview edit mode?

    thank you in advance.

  2. Stefan says:

    Hey,

    this part works only with the simple view, but how can it be done with the grouped table view?

    thanks!

  3. Digital Duane says:

    I’d like to request a simple “To Do” or Task list. This ‘iPhone SDK Tutorial – {Part 5}: Add, Delete & Reorder UITableView Rows’ could very easily be a To Do List, if one could edit the data being added, so that the same new item ‘Mac Mini’ is not being added, over and over when one clicks or touches the “add new row” button. The Keyboard should pop up and the user should be able to add the title of specifically whatever new item or task he or she wants to add.

    I like your nice, easy approach to these tutorials. if you could make a To Do List, with maybe a way to mark the task or item as complete and that is editable, you’d be like the King Of Po……no, the King of Tuts!

  4. yc says:

    Hi Adeem,

    Thank you for this tutorial. They are really helpful. I can now do a lot with uitableview.
    I would like to request 2 more on uitableview that I do not know how to implement .
    1 sort cells alphabetically, just like contact.
    2 two large images on the top, just like itunes.

    thank you very much

  5. geni says:

    Geni Likes it!

  6. Yara says:

    Hello,

    First thank you very much for all your effort on this sequence of tutorials. They have being very useful.

    I tried this tutorial and had a little problem when calling “addObject” over an NSArray “arryData”, it gives the following warning message:

    NSArray may not respond to -addObject
    (Messages without matching method signature will be assumed to return ‘id’ and accept ‘…’ arguments.)

    I changed NSArray to NSMutableArray, and it fixes. Not sure if I miss this in some point of the tutorial or not.

    Best Regards,

    yara senger

  7. Aaron says:

    When I add the
    - (IBAction)AddButtonAction:(id)sender{
    [arryData addObject:@"Mac Mini"];
    [tblSimpleTable reloadData];
    }

    - (IBAction)DeleteButtonAction:(id)sender{
    [arryData removeLastObject];
    [tblSimpleTable reloadData];
    }
    at the start it gave me an error :/

  8. Martin says:

    If you try to grab the “Add new item” and move it, the app crashes.

    I added the following to prevent moving of that item;

    - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row >= [arrayData count]) {
    return NO;
    }
    return YES;
    }

  9. Jordan says:

    Hi I’d like to know if it’s possible to changer the title label of the button “Delete” a row ?

    Thx
    Jordan

  10. umar says:

    Hi

    Thanks

    I started just programming for iPhone.
    I wanted to move UITableViewCell programmatic (without using edit button)

    Please help me.

  11. CT says:

    Thanks, awesome, helped me a lot in figuring table views

  12. Chris says:

    Hey, thanks for your guide, but I have a problem I do everything like you but when I want to add or do delete something the application stopped and closed.

    Can you help me pls?

  13. Lalo Ivol says:

    Hey! What a great tutorial! Is just what I needed… but… I’m getting this frustrating error, when trying to add or remove items: “-[__NSArrayI removeObjectAtIndex:]: unrecognized selector sent to instance 0x53498e0″

    I copy-pasted your code as similar as I could and I don’t understand what could be the difference between your code and mine. I’m getting the error in this method:

    - (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
    [self.items removeObjectAtIndex:indexPath.row]; // SIGABRT HERE
    [self.tableView reloadData];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
    [self.items insertObject:@"Aquí está la nueva tarea" atIndex:[self.items count]]; // AND HERE
    [self.tableView reloadData];
    }
    }

    Any guidance you can give to me? Thanks in advance!

  14. Leopold says:

    I am trying to make a view that looks like the periodic table with lots of small cells (which include logos that the user can click on to go to another screen) rather than rows that span the screen width. Is this possible with UITableView or do I need a different approach? Any help greatly appreciated, Leopold.

  15. Sohaila says:

    amazing :) thnx alot

Trackbacks for this post

  1. iPhone SDK Tutorial or Video Tutorial - {Part 4} Tips for UITableView Design [Add Header, Footer, background images & change design] | iPhone Diary | Tips
  2. iPhone SDK Tutorial + Video Tutorial - {Part 2} Navigation in UITableView | iPhone Diary | Tutorial
  3. iPhone SDK Tutorial – {Part 6}: Creating custom UITableViewCell Using Interface Builder [UITableView] | iPhone SDK Tutorial for Beginners | Tutorial
  4. iPhone Tutorial – {Part 7}: Adding Pictures into your table’s using Interface builder | iPhone SDK Tutorial for Beginners | Tips
  5. Complete List of UITableView UITableViewCell Tutorials + Video Tutorials | iPhone SDK Tutorial for Beginners | Tips
  6. iPhone SDK Tutorial + Video Tutorial - {Part 1} UITableView using NSArray | iPhone SDK Tutorial for Beginners | Tutorial
  7. iPhone SDK Tutorial + Video Tutorial - {Part 3} Grouped UITableView | iPhone SDK Tutorial for Beginners | Tutorial

Got something to say? Go for it!