Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert new cell into UITableView in Swift

I'm working on a project where I have two UITableViews and two UITextFields, when the user presses the button the data in the first textField should go into the tableView and the second go into the second tableView. My problem is that I don't know how to put data in the tableView each time the user pushes the button, I know how to insert data with tableView:cellForRowAtIndexPath: but that works for one time as far as I know. So what method can I use to update the tableView each time the user hits the button?

like image 256
code Horizons Avatar asked Aug 07 '15 05:08

code Horizons


People also ask

How do I add a cell in Swift?

Use beginUpdates and endUpdates to insert a new cell when the button clicked. Nice that you have provided the Objective-C version as well.

How do you add a row to a table view?

Step 1: Easiest way to add a new row The easiest way to add a new row to a UITableView would be to add a new item to the data and then call the reloadData method on the `UITableview. This will add a new row to our UITableView because we have added mercury to our data and then we called reloadData .

How can we use a reusable cell in UITableView?

For performance reasons, a table view's data source should generally reuse UITableViewCell objects when it assigns cells to rows in its tableView(_:cellForRowAt:) method. A table view maintains a queue or list of UITableViewCell objects that the data source has marked for reuse.


1 Answers

Use beginUpdates and endUpdates to insert a new cell when the button clicked.

As @vadian said in comment, begin/endUpdates has no effect for a single insert/delete/move operation

First of all, append data in your tableview array

Yourarray.append([labeltext])   

Then update your table and insert a new row

// Update Table Data tblname.beginUpdates() tblname.insertRowsAtIndexPaths([ NSIndexPath(forRow: Yourarray.count-1, inSection: 0)], withRowAnimation: .Automatic) tblname.endUpdates() 

This inserts cell and doesn't need to reload the whole table but if you get any problem with this, you can also use tableview.reloadData()


Swift 3.0

tableView.beginUpdates() tableView.insertRows(at: [IndexPath(row: yourArray.count-1, section: 0)], with: .automatic) tableView.endUpdates() 

Objective-C

[self.tblname beginUpdates]; NSArray *arr = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:Yourarray.count-1 inSection:0]]; [self.tblname insertRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationAutomatic]; [self.tblname endUpdates]; 
like image 68
EI Captain v2.0 Avatar answered Sep 23 '22 09:09

EI Captain v2.0