iOS Tutorials: Tableview Add w/ AlertController

OBJECTIVE

Create a tableview that can store a list of things that we insert. Here we will be using AlertController that pops up where we could type whatever we want and it will go into the table view. Note that the item inserted doesn’t stay in it unless we use Core Data or any sort of database. We are not using Core Data and Database here. For more information about core data, check out my other tutorial of Saving Notes using Core Data.

Create your project and let’s go straight into Main.storyboard to design our layout.

  1. Drag Navigation Bar with a top constant of 20
  2. Drag Navigation Item to the top right and pick Add for System Item
  3. Drag TableView and resize it 
  4. Drag Table View Cell onto Table View and rename the identifier into cell

We will need to use several protocol here such as UITableViewDataSource & UITableViewDelegate and with such, we will import the necessary function of Table View. But first, let’s create an IBOutlet for TableView, if you don’t know how to do that, you may check out my other tutorial of Introduction to IBAction & IBOutlet.

  1. Create an IBOutlet for TableView
  2. Create an array of String
  3. Connect Table View to Data Source and Delegate
import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet weak var tableView: UITableView!
    var lists: [String] = ["The first item"]
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
    }

We are then required to import the necessary functionality for UITableViewDataSource which is to determine how many rows are we going to have and what should we have on each row.

  1. We are telling the tableview to grab rows according to our array our lists. Let’s say if there are 10 objects in the array, show 10 rows.
  2. We are telling the tableview to look into our cell that we created by naming it cell. And we are telling the tableview to show all the objects on tableview
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return lists.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        cell?.textLabel?.text = lists[indexPath.row]
        return cell!
    }

We are still missing one more thing. We need to be able to add an object into the list. Remember the Navigation Item we created earlier with the Add image. Let’s create an IBAction from that Navigation Item.

Adding with Alert Controller

  1. We create an IBAction of the Navigation Item
  2. We create an Alert Controller with its title
  3. We create a Text Field where user could input any text
  4. We create an action that will put the value into the lists array and the tableview will refresh
  5. We create an action where you simply cancel
  6. Lastly, it will present the Alert Controller
@IBAction func addPressed(_ sender: UIBarButtonItem) {
        let alert = UIAlertController(title: "Add Content", message: "", preferredStyle: .alert)
        alert.addTextField { (UITextField) in
        }
        alert.addAction(UIAlertAction(title: "Add", style: .default, handler: { (UIAlertAction) in
            let content = alert.textFields![0] as UITextField
            self.lists.append(content.text!)
            self.tableView.reloadData()
        }))
        alert.addAction(UIAlertAction(title: "Cancel", style: .destructive, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }

Deleting from the list

Deleting is a really easy process, we just need to find out what is being removed on what row and remove it

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        
        if editingStyle == .delete {
            lists.remove(at: indexPath.row)
        }
        tableView.reloadData()
    }

 

The project is available on GitHub

 

  • Article By :
    Founder of DaddyCoding. Studied Computer Science, Information System and Information Technology at BYU-Hawaii. Currently spending most of my time researching and learning on helping to expose making iOS apps.

Random Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*