UItableview用法總結: 單元格刪除、添加方法、拖動單元格

#pragma mark-- 單元格刪除、添加方法,只要實現了此方法就能支持刪除了,但添加還需要其它

  • (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

{

if (editingStyle == UITableViewCellEditingStyleDelete) {

    //MVC => 數據是保存在模型中

    //刪除步驟1. 刪除 self.forumListArray 中 indexPath 對應的數據

    [self.forumListArray removeObjectAtIndex:indexPath.row];

    //刪除步驟2. 刷新表格 即重新加載所有數據

    [self.subTableView reloadData];

    //步驟2還可以寫成:

    //deleteRowsAtIndexPaths 是讓表格控件動畫刪除指定的行

// [self.subTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationMiddle)];

}else if (editingStyle == UITableViewCellEditingStyleInsert){

    //1.向數組添加數據

    [self.forumListArray insertObject:@"閆超志" atIndex:indexPath.row];

    //2.刷新表格

// [self.subTableView reloadData];

    //步驟2還可以寫成

    //新建一個indexpath

    NSIndexPath *path = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];

    [self.subTableView insertRowsAtIndexPaths:@[path] withRowAnimation:(UITableViewRowAnimationMiddle)];

}

}

#pragma mark-- tableview代理方法,添加cell的方法.注意:上面要添加協議,另外要先在viewdidload裏面將tableview設置成可編輯狀態

  • (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath

{

if (indexPath.row % 2) {

return UITableViewCellEditingStyleDelete;

}

return UITableViewCellEditingStyleInsert;

}

#pragma mark-- 單元格拖動方法

  • (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
    {
    [self.forumListArray exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章