如何重新加载和动画只有一个 UITableView 单元格/行?

我如何重新加载和动画只有一个单元格/行? 现在我下载了一些文件。每当一个文件完成下载,我调用它的完成委托和调用[ tableview reload ]。 但之后整张桌子都会重新装弹。我怎样才能让桌子动起来,这样它就不会眨眼了。例如淡出效果。

欢迎麦克斯

89097 次浏览

Use the following UITableView instance method:

- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

You have to specify an NSArray of NSIndexPaths that you want to reload. If you just want to reload. If you only want to reload one cell, then you can supply an NSArray that only holds one NSIndexPath. For example:

NSIndexPath* rowToReload = [NSIndexPath indexPathForRow:3 inSection:0];
NSArray* rowsToReload = [NSArray arrayWithObjects:rowToReload, nil];
[myUITableView reloadRowsAtIndexPaths:rowsToReload withRowAnimation:UITableViewRowAnimationNone];

You can see the UITableViewRowAnimation enum for all the possible ways of animating the row refresh. If you don't want any animation then you can use the value UITableViewRowAnimationNone, as in the example.

Reloading specific rows has a greater advantage than simply getting the animation effect that you'd like. You also get a huge performance boost because only the cells that you really need to be reloaded are have their data refreshed, repositioned and redrawn. Depending on the complexity of your cells, there can be quite an overhead each time you refresh a cell, so narrowing down the amount of refreshes you make is a necessary optimization that you should use wherever possible.

If you only need to update the text in the tableview cell..

UITableViewCell *cell = [_myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];


cell.textLabel.text = [NSString stringWithFormat:@"%i", (int)_targetMaxDistanceSlider.value];

Apple Document done it with new syntax

[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];

To reload particular cells in a tableView at given indexPaths, you need to create an array of indexPaths and then call function reloadRowsAtIndexPaths on the tableView.

Here is the example:

Swift 5:

let indexPathsToReload = [indexPath1, indexPath2, indexPath3]
tableView.reloadRows(at: indexPathsToReload, with: .none)

Objective C:

NSArray *indexPaths = @[indexPath1, indexPath2, indexPath3];
[self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];

or

NSArray *indexPaths = [NSArray arraywithobject:@"indexPath1", @"indexPath2", @"indexPath3",nil];
[self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];

Swift

You can use

let selectedIndexPath = IndexPath(item:0 , section: 0)
self.tableView.reloadRows(at: [selectedIndexPath], with: .none)

in order to reload a specific cell.

Swift 4 & 5

For TableView

let index = IndexPath(row: 0, section: 0)
tableView.reloadRows(at: [index], with: .automatic)

For CollectionView

let index = IndexPath(item: 2, section: 0)
collectionView.reloadItems(at: [index])