UI 第十一节 UITableView编辑

一.进入编辑模式

  • 通过直接设置UITableView的editing属性或向其发送setEditing:animated:消息,可将其置于编辑模式。
     self.tableview.editing = YES; [self.tableview setEditing:YES animated:YES]; 
  • UIViewController本身也有editing属性和setEditing:animated:方法,在当前视图控制器由导航控制器控制且导航栏中包含editButtonItem时,若UIViewController的editing为NO,则显示为”Edit”,若editing为YES,则显示为”Done”。


  • 可利用此按钮在设置UIViewController的editing状态时同时设置tableView的编辑状态。
    - (void)viewDidLoad {     [super viewDidLoad];     ....     self.navigationItem.rightBarButtonItem = self.editButtonItem; } -(void)setEditing:(BOOL)editing animated:(BOOL)animated {     [super setEditing:editing animated:animated];     [self.tableView setEditing:editing animated:animated]; }
    
  • 也可自定义其他按钮,将其响应设为修改tableView进入编辑模式。
    - (void)editAction:(id)sender {    [self.tableView setEditing:YES animated:YES]; }
    
  • UITableView接收到setEditing:animated:消息时,会发送同样的消息到所有可见的cell,设置其编辑模式。

    二.插入和删除

  • 进入编辑模式后,UITableView向其DataSource发送tableView:canEditRowAtIndexPath:消息询问每个indexPath是否可编辑,在此方法中对不可以编辑的cell返回NO,可以编辑的cell返回YES,若全部可编辑,可不实现,大部分应用不实现此方法。
    -(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {     if (indexPath.row == 1) {         return NO;     }     return YES; }
    
  • 然后,UITableView 向其delegate发送tableView:editingStyleForRowAtIndexPath:消息询问EditingStyle,这里返回删除(UITableViewCellEditingStyleDelete)或者插入(UITableViewCellEditingStyleInsert);若不实现此方法,则默认为删除模式,即UITableViewCellEditingStyleDelete。
    - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {     return UITableViewCellEditingStyleDelete;     //return UITableViewCellEditingStyleInsert; }
    

    当返回的是UITableViewCellEditingStyleDelete时,所有可编辑的Cell左侧都会显示红色的”减号”标示;

    点击左边的“减号”,减号会旋转90度变竖形,并且cell右侧出现”Delete”按钮。

    当返回的是UITableViewCellEditingStyleInsert时,在cell的左边会显示绿色”加号”按钮。

  • 当点击”Delete”按钮或者”加号”按钮时,UITableView向其DataSource发送tableView:commitEditingStyle:forRowAtIndexPath:消息,根据传递editingStyle来执行实际的删除或插入操作,其流程是先修改tableView的数据模型,向其中删除或插入对应数据项,然后再调整tableView的显示,删除或插入对应的cell。
    -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {     if (editingStyle == UITableViewCellEditingStyleDelete)     {         [dataArray removeObjectAtIndex:indexPath.row];         [tableview deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];     }else if(editingStyle == UITableViewCellEditingStyleInsert)     {         [dataArray insertObject:@"new Item" atIndex:indexPath.row];         [tableview insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];     } }
    

    当要删除或插入section时,需调用deleteSections:withRowAnimation:insertSections:withRowAnimation:方法。

posted @ 2016-02-23 13:46  lovecx  阅读(100)  评论(0编辑  收藏  举报