Ameya
Ameya

Reputation: 1960

UITableView add cell Animation

Can any one help me out with UITableView animating issue?

By default we have animation for deleting cell and reordering cells in UITableView.

Can we have animated adding cell, if so how to do it.

I have checked out Three20, did not not get how twitter has done the table expand animation under MyProfile>ReTweets.

Want to try it without Three20 frameowrk, using the existing animation in UITableView.

Upvotes: 37

Views: 42903

Answers (4)

Alejandro L.Rocha
Alejandro L.Rocha

Reputation: 1145

In swift is also possible using:

func insertRow(entries: [String]) {
    tableView.performBatchUpdates({
        self.tableView.insertRows(at: [IndexPath(row: entries.count - 1, section: 0)], with: .bottom)
    }, completion: nil)
}

Upvotes: 0

Suragch
Suragch

Reputation: 511646

Swift

Example array that is the data source for the table view

var myArray = ["Cow", "Camel", "Sheep", "Goat"]

The following will add a row with animation at the top of the table view.

// add item to current array
myArray.insert("Horse", atIndex: 0)

// insert row in table
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)

Multiple updates

If you need to do multiple insertions and/or deletions then surround them with beginUpdates() and endUpdates().

tableView.beginUpdates()
tableView.insertRowsAtIndexPaths([addIndexPath1, addIndexPath2, ...], withRowAnimation: .Fade)
tableView.deleteRowsAtIndexPaths([deleteIndexPath1, deleteIndexPath2, ...], withRowAnimation: .Fade)
tableView.endUpdates()

Further reading

Upvotes: 23

Use reloadRowsAtIndexPaths:indexPath

    tableView.beginUpdates()
    [tableView reloadRowsAtIndexPaths:indexPath withRowAnimation:UITableViewRowAnimationAutomatic];
    tableView.endUpdates()

i hope this will help you..

Upvotes: 0

RunLoop
RunLoop

Reputation: 20376

You can use the following UITableView method:

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

Example with self.dataSource being a mutable array and your table only having 1 section:

[self.dataSource addObject:@"New Item"];
NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:[self.dataSource count]-1 inSection:0];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];

Note: Subtracted 1 from datasource count since NSIndexPath is zero indexed.

Upvotes: 69

Related Questions