UITableView 編輯狀態(tài)(刪除、添加、移動)

----- TableView 刪除和添加 -----

   ** UITableView 編輯步驟
      1.讓 tableView 處于編輯狀態(tài)
      2.協(xié)議確定
          1)確定 cell 是否處于編輯狀態(tài)
          2)設定 cell 的編輯樣式(刪除、添加)
          3) 編輯狀態(tài)進行提交**
  
  • 開啟編輯狀態(tài)
      //1.讓 tableView 處于編輯狀態(tài)
      [tableView setEditing:YES animated:YES];
    

    如果沒有開啟編輯狀態(tài),沒有左邊的小紅點

Paste_Image.png
  • 1)確定 cell 是否處于編輯狀態(tài)
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
  return YES;
}
  • 2)設定 cell 的編輯樣式(刪除、添加)
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
        //插入
//    return UITableViewCellEditingStyleInsert;
    //刪除
    return UITableViewCellEditingStyleDelete;
}
  • 3) 編輯狀態(tài)進行提交
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (editingStyle) {
        case UITableViewCellEditingStyleNone:
        {
        }
            break;
        case UITableViewCellEditingStyleDelete:
        {
            //修改數(shù)據(jù)源,在刷新 tableView
            [_dataSource removeObjectAtIndex:indexPath.row];

            //讓表視圖刪除對應的行
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
            break;
        case UITableViewCellEditingStyleInsert:
        {
            [_dataSource insertObject:@"我是新增" atIndex:indexPath.row];
            //讓表視圖添加對應的行
            [tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
            break;

        default:
            break;
    }
}
  • 修改 Delete 文字
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"刪除";
}

刪除.gif
添加.gif

----- TableView 移動 -----

  • 1.實現(xiàn)協(xié)議:告訴 tableView 是否能夠移動
-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
  • 2.移動
-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    //修改數(shù)據(jù)源
    [_dataSource exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
    //讓表視圖對應的行進行移動
    [tableView exchangeSubviewAtIndex:sourceIndexPath.row withSubviewAtIndex:destinationIndexPath.row];
}
移動.gif
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容