ios 使用 moveRowAtIndexPath:toIndexPath: 正确 [英] ios using moveRowAtIndexPath:toIndexPath: correctly

查看:41
本文介绍了ios 使用 moveRowAtIndexPath:toIndexPath: 正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我正在制作一个待办事项列表应用程序.我只是想知道如何正确使用 moveRowAtIndexPath:toIndexPath: 因为如果 toDoItemCompleted 方法被触发,它会一直崩溃.一旦方法被触发,我试图将一行移到列表的底部.

Okay so I'm making a to do list app. I'm just wondering how to use moveRowAtIndexPath:toIndexPath: properly since it keeps crashing if the toDoItemCompleted method is triggered. I'm trying to move a row down to the bottom of the list once the method is triggered.

-(void)toDoItemCompleted:(ToDoItem *)todoItem {
    NSUInteger origIndex = [_toDoItems indexOfObject:todoItem];
    NSIndexPath *origIndexPath = [[NSIndexPath alloc]initWithIndex:origIndex];

    NSUInteger endIndex = _toDoItems.count-1;
    NSIndexPath *endIndexPath = [[NSIndexPath alloc]initWithIndex:endIndex];

    [self.tableView beginUpdates];
    [self.tableView moveRowAtIndexPath:origIndexPath toIndexPath:endIndexPath];
    [self.tableView endUpdates];
}

推荐答案

你不说错误是什么.您应该发布完整的错误并指出实际导致错误的代码行.

You don't say what the error is. You should post the full error and point out which line of code is actually causing the error.

但是您的代码存在的一个问题是您忘记更新数据源.这需要在更新表视图之前完成.

But one issue with your code is that you forgot to update your data source. This needs to be done before updating the table view.

另一个问题是如何创建索引路径.

Another issue is with how you create the index paths.

像这样:

- (void)toDoItemCompleted:(ToDoItem *)todoItem {
    NSUInteger origIndex = [_toDoItems indexOfObject:todoItem];
    NSIndexPath *origIndexPath = [NSIndexPath indexPathForRow:origIndex inSection:0];

    NSUInteger endIndex = _toDoItems.count - 1;
    NSIndexPath *endIndexPath = [NSIndexPath indexPathForRow:endIndex inSection:0];

    // Update date source
    [_toDoItems removeObject:todoItem]; // remove from current location
    [_toDoItems addObject:todoItem]; // add it to the end of the list

    [self.tableView beginUpdates];
    [self.tableView moveRowAtIndexPath:origIndexPath toIndexPath:endIndexPath];
    [self.tableView endUpdates];
}

这篇关于ios 使用 moveRowAtIndexPath:toIndexPath: 正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆