How to insert new cell into UITableView in Swift

IosIphoneSwiftUitableview

Ios Problem Overview


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?

Ios Solutions


Solution 1 - Ios

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];

Solution 2 - Ios

Swift 5.0, 4.0, 3.0 Updated Solution

Insert at Bottom

self.yourArray.append(msg)
                                   
self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: self.yourArray.count-1, section: 0)], with: .automatic)
self.tblView.endUpdates()

Insert at Top of TableView

self.yourArray.insert(msg, at: 0)
self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: 0, section: 0)], with: .automatic)
self.tblView.endUpdates()

Solution 3 - Ios

Here is your code for add data into both tableView:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var table1Text: UITextField!
    @IBOutlet weak var table2Text: UITextField!
    @IBOutlet weak var table1: UITableView!
    @IBOutlet weak var table2: UITableView!
    
    var table1Data = ["a"]
    var table2Data = ["1"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
    }
    
    @IBAction func addData(sender: AnyObject) {
        
        //add your data into tables array from textField
        table1Data.append(table1Text.text)
        table2Data.append(table2Text.text)
        
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            //reload your tableView
            self.table1.reloadData()
            self.table2.reloadData()
        })
        
        
        table1Text.resignFirstResponder()
        table2Text.resignFirstResponder()
    }
    
    //delegate methods
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == table1 {
            return table1Data.count
        }else if tableView == table2 {
            return table2Data.count
        }
        return Int()
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        if tableView == table1 {
            let cell = table1.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
            
            let row = indexPath.row
            cell.textLabel?.text = table1Data[row]
            
            return cell
        }else if tableView == table2 {
            
            let cell = table2.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath) as! UITableViewCell
            
            let row = indexPath.row
            cell.textLabel?.text = table2Data[row]
            
            return cell
        }
        
        return UITableViewCell()
    }
}

And your result will be:

enter image description here

Solution 4 - Ios

For Swift 5

Remove Cell

    let indexPath = [NSIndexPath(row: yourArray-1, section: 0)]
    yourArray.remove(at: buttonTag)
    self.tableView.beginUpdates()

    self.tableView.deleteRows(at: indexPath as [IndexPath] , with: .fade)
    self.tableView.endUpdates()
    self.tableView.reloadData()// Not mendatory, But In my case its requires

Add new cell

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

Solution 5 - Ios

You can find this comment in Apple's UITableView framework:

// Use -performBatchUpdates:completion: instead of these methods, which will be deprecated in a future release.

So, you should use this:

tableView.performBatchUpdates { [unowned self] in
    tableView.insertRows(at: indexPaths, with: animation)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioncode HorizonsView Question on Stackoverflow
Solution 1 - IosBhavin BhadaniView Answer on Stackoverflow
Solution 2 - IosSourabh SharmaView Answer on Stackoverflow
Solution 3 - IosDharmesh KheniView Answer on Stackoverflow
Solution 4 - IosShourob DattaView Answer on Stackoverflow
Solution 5 - IosVictor MoreiView Answer on Stackoverflow