moveRowAtIndexPath - Moving cells between sections

前端 未结 2 1871
花落未央
花落未央 2021-01-06 20:53

In my UITableView I have this said relationship

Department -< Employees (array of names)

I have set up custom objects for each model.

2条回答
  •  猫巷女王i
    2021-01-06 21:29

    Your problem is that you have manipulated the data model, but you haven't told the tableview about the changes you made.

    Because you call beginUpdates/endUpdates the tableview is expecting some changes, so after endUpdates it calls numberOfRowsInSection - which returns the answer '3' - but it is expecting 2+0 (because you didn't tell it about the new row).

    You have a couple of options:

    1 - Use moveRowAtIndexPath:toIndexPath:

    - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
    {
        if (fromIndexPath != toIndexPath ) {
    
            Department *department = [_objects objectAtIndex:fromIndexPath.section];
            Employee *employee = [department.employees objectAtIndex:fromIndexPath.row];
    
            [tableView beginUpdates];
            [department.employees removeObjectAtIndex:fromIndexPath.row];
            [department.employees insertObject:employee atIndex:toIndexPath.row];
            [tableview moveRowAtIndexPath:fromIndexPath toIndexPath:toIndexPath];
            [self.tableView endUpdates];
        }
    }
    

    2 - Use reload without the beginUpdate/endUpdate

    - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
    {
        if (fromIndexPath != toIndexPath ) {
    
            Department *department = [_objects objectAtIndex:fromIndexPath.section];
            Employee *employee = [department.employees objectAtIndex:fromIndexPath.row];
    
            [department.employees removeObjectAtIndex:fromIndexPath.row];
            [department.employees insertObject:employee atIndex:toIndexPath.row];
            [tableView reloadData];
        }
    }
    

提交回复
热议问题