Insertions and deletions in a Table View


Insert, delete, and reorder the UITableViewCells of a UITableView. The last cell is always green, the others are red.

Source code in

  1. main.m
  2. Class AppDelegate
  3. Class TableViewController

Things to Try

  1. If we press the Done button in the navigation bar while a keyboard is visible, the keyboard should be dismissed. Add the following method to the TableViewController.
    //Will be called when the Edit/Done button is pushed.
    - (void) buttonPushed: (id) sender
    	//Do what the Edit/Done button normally does.
    	[self.tableView setEditing: !self.tableView.editing animated: YES];
    	((UIBarItem *)sender).title =
    		self.tableView.editing ? @"Done" : @"Edit";
    	//In addition, dismiss the keyboard.
    	if (changing != nil) {
    		UITableViewCell *cell =
    			[self.tableView cellForRowAtIndexPath: changing];
    		UITextField *textField = [cell.contentView.subviews lastObject];
    		[textField resignFirstResponder];
    		[textField removeFromSuperview];
    		changing = nil;
    Add the following statements to the end of the viewDidLoad method of the TableViewController. = self;
    	self.editButtonItem.action = @selector(buttonPushed:);

  2. If we drag the bottom cell up to a new position, the green plus should move back down to the new bottom cell. Add the following code to the end of the tableView:moveRowAtIndexPath:toIndexPath: method of the TableViewController.
    	--If the cell that was just dragged was the bottom cell,
    	if (fromIndexPath.row == lines.count - 1) {
    		[tableView reloadData];