Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // ViewController.swift
- // Todoey
- //
- // Created by Jessamine Briones on 16/1/19.
- // Copyright © 2019 Jessamine Briones. All rights reserved.
- //
- import UIKit
- class ToDoListViewController: UITableViewController {
- var itemArray = [Item]()
- let defaults = UserDefaults.standard
- let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("Items.plist")
- override func viewDidLoad() {
- super.viewDidLoad()
- print (dataFilePath)
- let newItem = Item()
- newItem.title = "Buy dumplings"
- itemArray.append(newItem)
- let newItem2 = Item()
- newItem2.title = "Go to the beach"
- itemArray.append(newItem2)
- let newItem3 = Item()
- newItem3.title = "Buy ice cream"
- itemArray.append(newItem3)
- if let items = defaults.array(forKey: "ToDoListArray") as? [Item] {
- itemArray = items
- }
- // Do any additional setup after loading the view, typically from a nib.
- }
- override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- return itemArray.count
- }
- override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoItemCell", for: indexPath)
- let item = itemArray[indexPath.row]
- cell.textLabel?.text = item.title
- cell.accessoryType = item.done ? .checkmark : .none
- return cell
- }
- override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
- itemArray[indexPath.row].done = !itemArray[indexPath.row].done
- saveItems()
- tableView.deselectRow(at: indexPath, animated: true)
- }
- //MARK - Add New Items
- @IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
- var textField = UITextField()
- let alert = UIAlertController(title: "Add New Todoey Item", message: "", preferredStyle: .alert)
- let action = UIAlertAction(title: "Add Item", style: .default) { (action) in
- // what happens once user clicks add button in ui alert
- let newItem = Item()
- newItem.title = textField.text!
- self.itemArray.append(newItem)
- self.saveItems()
- }
- self.tableView.reloadData()
- alert.addTextField { (alertTextField) in
- alertTextField.placeholder = "Create new item"
- textField = alertTextField
- // extending the scope of the alertTextField by assigning var textField to it
- }
- alert.addAction(action)
- present(alert, animated: true, completion: nil)
- }
- func saveItems() {
- let encoder = PropertyListEncoder()
- do {
- let data = try encoder.encode(itemArray)
- try data.write(to: dataFilePath!)
- } catch {
- print("Error encoding item array, \(error)")
- }
- }
- }
Add Comment
Please, Sign In to add comment