使用reloadData与动画效果

3

在我的UITableView实例中,我将单元格移动到索引:0并重新加载数据。问题是单元格“捕捉”到顶部(由于reloadData,我认为)。我想知道是否可以将单元格向上移动,然后再过几秒钟应用reloadData。这是我的代码:

[_toDoItems removeObject:todoItem];

[_toDoItems insertObject:todoItem atIndex:0 ];





[self.tableView beginUpdates];

[self.tableView moveRowAtIndexPath:origIndexPath toIndexPath:0];

[self.tableView endUpdates];

sleep(1);
[self.tableView reloadData];

这样做的问题是,在方法调用后,一切都会暂停1秒钟,然后才会发生“快照”动画。

1
sleep(1); 的作用是什么?把它删除。 - Souljacker
3
不应使用sleep()。它会阻塞所有线程,包括处理所有视觉效果的主线程。因此你会看到它等待一秒钟,然后突然跳转。这个跳转只是在等待其线程被解锁。另外,由于reloadData没有任何动画效果,所以会产生“突然跳转”的效果。 - Firo
我的逻辑是,该单元格将被移动到顶部;然后睡眠将延迟1秒钟的reloadData。 - Brian
3个回答

1

首先使用 beginUpdates 告诉 tableView 准备更新。然后更新相关部分(如果你的 tableView 只有一个部分,则只需将部分号码传递为零)。这里是您指定动画效果的地方 - 您可以尝试不同的效果来获得所需的效果。之后在 tableView 上调用 endUpdatesUITableViewRowAnimation 的 typedef 指定:

typedef enum {
   UITableViewRowAnimationFade,
   UITableViewRowAnimationRight,
   UITableViewRowAnimationLeft,
   UITableViewRowAnimationTop,
   UITableViewRowAnimationBottom,
   UITableViewRowAnimationNone,
   UITableViewRowAnimationMiddle,
   UITableViewRowAnimationAutomatic = 100
} UITableViewRowAnimation;

尝试一下,看看你想要哪一个。有时候即使选择UITableViewRowAnimationNone也会产生不错的效果。根据你有多少个章节,你可以使用- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation

以下是表格更新代码:

[self.tableView beginUpdates];
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];

@brain 如果您发现任何答案有用,请点赞,如果答案正确,请接受它,这将有助于从未回答的问题列表中删除该问题。 - icodebuster

1
解决了。
     [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(briefPause) userInfo:nil repeats:NO];

我使用了上述代码,与同一方法中的代码相同

[self.tableView beginUpdates]
....

但我创建了一个新的函数,briefPause,它只是:

    [self.tableView reloadData];

它确实可以工作,但我建议使用更少的时间:[NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(briefPause) userInfo:nil repeats:NO];它仍然可以工作,但看起来会更流畅。 - Renexandro

0

试试这个:

[self.tableView beginUpdates];
[self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:origIndexPath
                                                       inSection:0]]
                 withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0
                                                       inSection:0]]
                 withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tableView endUpdates];

2
正如其他人在上面提到的,不要使用sleep()。我禁止它! :) - Guy Kogus
即使将 withRowAnimation 调整为其他值,也无法真正解决问题。这可以防止奇怪的抖动/闪烁,但单元格只是在顶部瞬间出现而没有动画效果。 :/ - Brian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接