Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically add rows to a specific UITableView section?

I am a new IOS Programmer, and i am having a issue.

I have a UITableView with 2 sections, one then is static, and another one is dynamical.

In specific actions i need to add new rows for the second section in runtime..

I know how to manage a UITableView , but not a specific section

Could you help me please?

Best Regards you all

like image 834
vmfesta Avatar asked May 23 '14 04:05

vmfesta


3 Answers

You can use insertRowsAtIndexPaths: method of UITableView

//Update data source with the object that you need to add
[tableDataSource addObject:newObject];

NSInteger row = //specify a row where you need to add new row
NSInteger section = //specify the section where the new row to be added, 
//section = 1 here since you need to add row at second section

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
[self.tableView endUpdates];
like image 82
Akhilrajtr Avatar answered Oct 27 '22 00:10

Akhilrajtr


You can use the same method insertRowAtIndexPath like

 // Add the items into your datasource object first. Other wise you will end up with error
 // Manage the number of items in section. Then do

 NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:0 inSection:1];
 NSIndexPath *indexPath2 = [NSIndexPath indexPathForRow:1 inSection:1];
[self.tableView insertRowsAtIndexPaths:@[indexPath1,indexPath2] withRowAnimation:UITableViewRowAnimationTop];

This will insert two rows to the section1. Remember before doing this you have manage your datasource object.

like image 39
Anil Varghese Avatar answered Oct 27 '22 00:10

Anil Varghese


Swift 3 version

// Adding new item to your data source
dataSource.append(item)
// Appending new item to table view
yourTableView.beginUpdates()
// Creating indexpath for the new item
let indexPath = IndexPath(row: dataSource.count - 1, section: yourSection)
// Inserting new row, automatic will let iOS to use appropriate animation 
yourTableView.insertRows(at: [indexPath], with: .automatic)
yourTableView.endUpdates()
like image 23
Anand Avatar answered Oct 27 '22 00:10

Anand