All about TableViews

Sept 20, 2017   3 minutes to read



Part 2: Adding Elements

1
Now that our TableView is able to list elements (see Part 1), we are going to implement the functionality to add elements to the list.

There are many ways to implement the adding functionality to our table view. In this case we are simply going to add a Navigation Bar with a Bar Button above our table view. When the Bar Button is pressed, a alert with 2 text input fields (e.g. Firstname, Lastname) and 2 buttons (Save and Cancel) is displayed.

First, we should consider to resize the Table View in our Main.storyboard, such that the Navigation Bar can be placed above it (Figure 1).

Fig. 1Resizing the Table View height in the Main.storyboard file of our Xcode Project.



First drag the Navigation Bar and then the Bar Button from the Object Library and place it in the previously allocated space. For demonstration purpose we will rename the title of the Navigation Bar to "Employees" and change the "System Item" property inside of the Attributes Inspector of our Bar Button from "Custom" to "Add" (See Fig. 2).

Fig. 2Screencast of the Main Storyboard in Xcode. Placing the Interface Elements and specifying them appropriately.



2
In order to interact with the Add Button, we need to connect (ctrl-drag) it as an IBAction to our ViewController.swift file. For this, the "Assistent Editor" view comes handy, as it allows us to see our source code and storyboard side by side (see Fig. 3).

Fig. 3Screencast of the Main Storyboard Assistent Editor View in Xcode. Connecting the BarButton as an IBAction to our ViewController.swift file.



3
Inside the IBAction function (addEmployee) we are going to create an alert with 2 buttons (Cancel, Save) and 1 text input field (Firstname). Since this process has been covered in one of the articles (see Article: Basic Alerts), we won't cover it in detail and provide the necessary code instead.
@IBAction func addEmployee(_ sender: UIBarButtonItem) {
      let alert = UIAlertController(title: "Add Employee", message: "Enter firstname and lastname", preferredStyle: .alert)
      
      alert.addTextField(configurationHandler: nil)
      
      let save = UIAlertAction(title: "Save", style: .default){
          (alertAction: UIAlertAction) in
          
          if let textField1 = alert.textFields?[0].text{
              self.data.append(textField1)
          }
          
      }
      
      let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
      
      alert.addAction(save)
      alert.addAction(cancel)

      self.present(alert, animated: true, completion: nil)
}

4
Notice that we append the text field input to our data array whenever the save button is pressed, however it is currently not displayed in our table view. In order for it to be displayed we have to refresh the table view. Therefore we need a reference (IBOutlet) to the table view in our "ViewController.swift" (see Fig. 4).

Fig. 3Screencast of the Main Storyboard Assistent Editor View in Xcode. Connecting the Table View as an IBOutlet to our ViewController.swift file.


Once the reference IBOutled is created, we can go back to our "AddEmployee" IBAction and insert the following line right after appending the input string into our data array:
self.myTableView.reloadData()
As a result we are now capable of adding elements to our table view.

Final Source Code:

//
//  ViewController.swift
//
import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet weak var myTableView: UITableView!
    
    var data = ["John", "Carl", "Kenny"]

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier:
        "Cell", for: indexPath)
        cell.textLabel?.text = data[indexPath.row]
        
        return cell
    }
    
    @IBAction func addEmployee(_ sender: UIBarButtonItem) {
        let alert = UIAlertController(title: "Add Employee", message: "Enter firstname and lastname", preferredStyle: .alert)
        
        alert.addTextField(configurationHandler: nil)
        
        let save = UIAlertAction(title: "Save", style: .default){
            (alertAction: UIAlertAction) in
            
            if let textField1 = alert.textFields?[0].text{
                self.data.append(textField1)
                self.myTableView.reloadData()
            }
            
        }
        
        let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
        
        alert.addAction(save)
        alert.addAction(cancel)

        self.present(alert, animated: true, completion: nil)
        
    }
    
}