IOS development-private address book editing style(60)

I. Overview

This article mainly introduces the content:

  • Add a delete button on the right side of the navigation bar (there is an add button)
  • Click the delete button to delete the tableview entry
  • Call before tableview editing, switch the editing mode in tableview (add, delete mode)

Two renderings

Add a delete button to the right of the three navigation bar (there is an add button)

3.1 Add through Main.storyboard

  • Click "+" at the top of Xcode, select BarButtonItem, and select Trash for System item

     

3.2 Add by code

Business logic

  • Now get the "add" button in the layout
  • Create a "delete" button through code
  • Add the above two buttons through aviationItem.rightBarButtonItems

Code

1
2
3
4
5
6
//Get + button
UIBarButtonItem *add=self.navigationItem.rightBarButtonItem;
   
//Add a trash can button
UIBarButtonItem *trash=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemTrash    target:self action:@selector(delete)];
self.navigationItem.rightBarButtonItems=@[add,trash];

Four click the delete button to delete the tableview entry

4.1 Logic Description

  • Set the edit mode for the tableview, when you click the delete button, switch the edit mode of the tableview
  • When the editing mode is delete, the commitEditingStyle method will be called to update the data and layout operations

4.2 Code implementation

delete method

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

commitEditingStyle

1
2
3
4
5
//delete data
[self.contacts removeObjectAtIndex:indexPath.row];
//Refresh the interface
//[self.tableView reloadData];//Global refresh
[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];//删除局部

Five switch the editing mode in the tableview (add, delete mode)

5.1 Logic description

  • The tableview will call the editingStyleForRowAtIndexPath method before editing, which can set the style for the entries in the tableview
  • For example, entry 0 is UITableViewCellEditingStyleInsert, the others are UITableViewCellEditingStyleDelete
  • Add the corresponding function to the corresponding style

5.2 Code implementation

editingStyleForRowAtIndexPath

1
2
3
4
5
6
7
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        return UITableViewCellEditingStyleInsert;
    }
    return UITableViewCellEditingStyleDelete;
}

UITableViewCellEditingStyleInsert

1
2
3
4
Contact *contact=[Contact contactWithName:@"grace" phone:@"123"];
//[self.contacts addObject:contact];//Add to the last line
[self.contacts insertObject:contact atIndex:indexPath.row+1];
[self.tableView reloadData];

Guess you like

Origin blog.csdn.net/Calvin_zhou/article/details/109140073