code Horizons code Horizons - 6 months ago 26
Swift Question

How to insert new cell into UITableView in Swift

I'm working on a project where I have two

UITableView
s and two
UITextField
s, 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?

Answer

Try this.....

Use beginUpdates and endUpdates for insert new cell when button clicked..

First of all append data in your tableview array

    Yourarray.append([labeltext])  

Then upate your table and insert 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 whole table but If you get any problem with this,you can also use tableview.reloadData()

Objective-c

[self.tblname beginUpdates];
[self.tblname insertRowsAtIndexPaths:[your index path] withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tblname endUpdates];