Guest User

Untitled

a guest
Feb 15th, 2020
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 11.80 KB | None | 0 0
  1. tableViewController.swift:
  2. import UIKit
  3. import os.log
  4.  
  5. class TableViewController: UITableViewController {
  6.  
  7.     //temp list of tasks
  8.     var tasks = [task]()
  9.    
  10.    
  11.    
  12.     override func viewDidLoad() {
  13.         super.viewDidLoad()
  14.  
  15.         // Uncomment the following line to preserve selection between presentations
  16.         // self.clearsSelectionOnViewWillAppear = false
  17.  
  18.         // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
  19.         //self.navigationItem.leftBarButtonItem = self.editButtonItem
  20.        
  21.         //giving some default values in the cell
  22.         //tasks += ["something"]
  23.        
  24.         loadSampleTasks()
  25.        
  26.     }
  27.  
  28.     // MARK: - Table view data source
  29.  
  30.     override func numberOfSections(in tableView: UITableView) -> Int {
  31.         // #warning Incomplete implementation, return the number of sections
  32.         return 1
  33.     }
  34.  
  35.     override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  36.         // #warning Incomplete implementation, return the number of rows
  37.         return tasks.count
  38.     }
  39.    
  40.    
  41.  
  42.     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  43.         let cell = tableView.dequeueReusableCell(withIdentifier: "simpleCell", for: indexPath)
  44.  
  45.         // Configure the cell...
  46.         let row = indexPath.row
  47.        
  48.         cell.textLabel?.text = tasks[row].title
  49.        
  50.         //makes the cell background gray if its done
  51.         if tasks[row].done {
  52.             cell.backgroundColor = UIColor.lightGray
  53.         }
  54.        
  55.        
  56.    
  57.         return cell
  58.     }
  59.  
  60.    
  61.     // Override to support conditional editing of the table view.
  62.     override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
  63.         // Return false if you do not want the specified item to be editable.
  64.         return true
  65.     }
  66.    
  67.  
  68.    
  69.     // Override to support editing the table view.
  70.     override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
  71.         if editingStyle == .delete {
  72.             // Delete the row from the data source
  73.             tasks.remove(at: indexPath.row)
  74.             tableView.deleteRows(at: [indexPath], with: .fade)
  75.         } else if editingStyle == .insert {
  76.             // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
  77.         }
  78.     }
  79.    
  80.     //leading swipe for editing code
  81.     override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  82.    
  83.         let edit = UIContextualAction(style: .normal, title: "Edit") { (contextualAction, view, actionPerformed: (Bool) -> ()) in
  84.             self.performSegue(withIdentifier: "showDetail", sender: UITableViewCell())
  85.             actionPerformed(true)
  86.            
  87.         }
  88.        
  89.         return UISwipeActionsConfiguration(actions: [edit])
  90.     }
  91.    
  92.  
  93.     /*
  94.     // Override to support rearranging the table view.
  95.     override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
  96.  
  97.     }
  98.     */
  99.  
  100.     /*
  101.     // Override to support conditional rearranging of the table view.
  102.     override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
  103.         // Return false if you do not want the item to be re-orderable.
  104.         return true
  105.     }
  106.     */
  107.  
  108.    
  109.      
  110.     // MARK: -Action
  111.     @IBAction func unwindToTaskList(sender: UIStoryboardSegue) {
  112.         if let sourceViewController = sender.source as? ViewController, let task = sourceViewController.Task {
  113.            
  114.             if let selectedIndexPath = tableView.indexPathForSelectedRow {
  115.                 // Update an existing task.
  116.                 tasks[selectedIndexPath.row] = task
  117.                 tableView.reloadRows(at: [selectedIndexPath], with: .none)
  118.             }else {
  119.                 // Add a new meal.
  120.                 let newIndexPath = IndexPath(row: tasks.count, section: 0)
  121.                
  122.                 tasks.append(task)
  123.                 tableView.insertRows(at: [newIndexPath], with: .automatic)
  124.             }
  125.         }
  126.     }
  127.      
  128.    
  129.     // MARK: - Navigation
  130.  
  131.    
  132.     // In a storyboard-based application, you will often want to do a little preparation before navigation
  133.     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  134.        
  135.         // Get the new view controller using segue.destination.
  136.         // Pass the selected object to the new view controller.
  137.         super.prepare(for: segue, sender: sender)
  138.        
  139.         switch(segue.identifier ?? "") {
  140.            
  141.             case "addItem":
  142.             os_log("Adding a new task.", log: OSLog.default, type: .debug)
  143.            
  144.             case "showDetail":
  145.             guard let ViewController = segue.destination as? ViewController else {
  146.                 fatalError("Unexpected destination: \(segue.destination)")
  147.             }
  148.              
  149.             guard let selectedTaskCell = sender as? taskCellTableViewCell else {
  150.                 fatalError("Unexpected sender: \(sender)")
  151.             }
  152.              
  153.             guard let indexPath = tableView.indexPath(for: selectedTaskCell) else {
  154.                 fatalError("The selected cell is not being displayed by the table")
  155.             }
  156.              
  157.             let selectedTask = tasks[indexPath.row]
  158.             ViewController.Task = selectedTask
  159.            
  160.             default:
  161.             fatalError("Unexpected Segue Identifier; \(segue.identifier)")
  162.            
  163.         }
  164.     }
  165.    
  166.     private func loadSampleTasks(){
  167.        
  168.                let formatter = DateFormatter()
  169.                formatter.dateFormat = "MM/dd/yyyy"
  170.                let date = formatter.date(from: "02/28/2020")
  171.        
  172.         guard let task1 = task(title: "call mom", done: false, date: date! )else{ fatalError("fuck you")}
  173.        
  174.         tasks += [task1]
  175.     }
  176.    
  177. }
  178.  
  179. viewController aka the detail screen:
  180. import UIKit
  181. import os.log
  182.  
  183. class ViewController: UIViewController, UITextFieldDelegate {
  184.  
  185.     @IBOutlet weak var taskTitleTextField: UITextField!
  186.     @IBOutlet weak var taskLabel: UILabel!
  187.     @IBOutlet weak var saveButton: UIBarButtonItem!
  188.    
  189.     @IBOutlet weak var doneSwitch: UISwitch!
  190.    
  191.     //code for the done button
  192.     @IBAction func doneButton(_ sender: UIBarButtonItem){
  193.        
  194.         let isPresentingInAddMealMode = presentingViewController is UINavigationController
  195.        
  196.         if isPresentingInAddMealMode {
  197.         dismiss(animated: true, completion: nil)
  198.         }else if let owningNavigationController = navigationController{
  199.             owningNavigationController.popViewController(animated: true)
  200.         }else {
  201.             fatalError("The MealViewController is not inside a navigation controller.")
  202.         }
  203.     }
  204.    
  205.    
  206.     //gobal datePicker and toolbar for the date
  207.     var toolBar = UIToolbar()
  208.     var datePicker  = UIDatePicker()
  209.    
  210.     var dateString : String = "" //holds the dateString for the button title
  211.    
  212.     @IBOutlet weak var titleHolder: UIButton!
  213.    
  214.     //shows the date picker when the button is pushed
  215.     @IBAction func datePickerButton(_ sender: UIButton) {
  216.        
  217.        datePicker = UIDatePicker.init()
  218.        datePicker.backgroundColor = UIColor.white
  219.  
  220.        datePicker.autoresizingMask = .flexibleWidth
  221.        datePicker.datePickerMode = .date
  222.  
  223.        datePicker.addTarget(self, action: #selector(self.dateChanged(_:)), for: .valueChanged)
  224.        datePicker.frame = CGRect(x: 0.0, y: UIScreen.main.bounds.size.height - 300, width: UIScreen.main.bounds.size.width, height: 300)
  225.        self.view.addSubview(datePicker)
  226.  
  227.        toolBar = UIToolbar(frame: CGRect(x: 0, y: UIScreen.main.bounds.size.height - 300, width: UIScreen.main.bounds.size.width, height: 50))
  228.        toolBar.isTranslucent = true
  229.        
  230.        toolBar.items = [UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.onDoneButtonClick))]
  231.        
  232.        toolBar.sizeToFit()
  233.        self.view.addSubview(toolBar)
  234.        
  235.         //sets the button to the date
  236.         //sender.setTitle(dateString, for: .normal)
  237.     }
  238.    
  239.     //updates the due date
  240.     @objc func dateChanged(_ sender: UIDatePicker?) {
  241.  
  242.         if let date = sender?.date {
  243.             Task?.date = date
  244.             dateString = dateToString(date: date)
  245.         }
  246.     }
  247.  
  248.     @objc func onDoneButtonClick() {
  249.         toolBar.removeFromSuperview()
  250.         datePicker.removeFromSuperview()
  251.         titleHolder.setTitle(dateString, for: .normal)
  252.     }
  253.    
  254.     //the task that gets sent back after saving
  255.     var Task: task?
  256.    
  257.     override func viewDidLoad() {
  258.         super.viewDidLoad()
  259.         // Do any additional setup after loading the view.
  260.        
  261.         // Handle the text field’s user input through delegate callbacks.
  262.         taskTitleTextField.delegate = self
  263.        
  264.         // Set up views if editing an existing task.
  265.         if let Task = Task {
  266.             navigationItem.title = Task.title
  267.             taskTitleTextField.text = Task.title
  268.             taskLabel.text = Task.title
  269.             doneSwitch.isOn = Task.done
  270.             titleHolder.setTitle(dateToString(date: Task.date), for: .normal)
  271.            
  272.         }
  273.        
  274.         // Enable the Save button only if the text field has a valid task title.
  275.         updateSaveButtonState()
  276.     }
  277.    
  278.     func textFieldShouldReturn(_ textField: UITextField) -> Bool {
  279.         //hides the keyboard and stops the textField from being the first responder
  280.         textField.resignFirstResponder()
  281.         return true
  282.     }
  283.    
  284.     func textFieldDidEndEditing(_ textField: UITextField) {
  285.        
  286.         taskLabel.text = textField.text
  287.        
  288.         updateSaveButtonState()
  289.         navigationItem.title = textField.text
  290.     }
  291.    
  292.     // This method lets you configure a view controller before it's presented.
  293.     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  294.        
  295.         super.prepare(for: segue, sender: sender)
  296.        
  297.         guard let button = sender as? UIBarButtonItem, button === saveButton else {
  298.             os_log("the save button was not pressed to get here, stopping", log: OSLog.default, type: .debug)
  299.             return
  300.         }
  301.        
  302.         let title = taskTitleTextField.text ?? ""
  303.         let date = Task?.date ?? Date()
  304.         let done = doneSwitch.isOn
  305.        
  306.         Task = task(title: title, done: done, date: date)
  307.        
  308.     }
  309.    
  310.     //MARK: Save Button
  311.     //ensures new information was given when saving
  312.     func textFieldDidBeginEditing(_ textField: UITextField) {
  313.         // Disable the Save button while editing.
  314.         saveButton.isEnabled = false
  315.     }
  316.    
  317.     private func updateSaveButtonState() {
  318.         // Disable the Save button if the text field is empty.
  319.         let text = taskTitleTextField.text ?? ""
  320.         saveButton.isEnabled = !text.isEmpty
  321.     }
  322.    
  323.     //func for converting a date to a string
  324.     func dateToString(date: Date) -> String{
  325.         let formatter = DateFormatter()
  326.         formatter.dateFormat = "MM/dd/yyyy"
  327.        
  328.         return formatter.string(from: date)
  329.     }
  330. }
  331.  
  332. tableViewCell.swift:
  333. import UIKit
  334.  
  335. class taskCellTableViewCell: UITableViewCell {
  336.  
  337.     override func awakeFromNib() {
  338.         super.awakeFromNib()
  339.         // Initialization code
  340.     }
  341.  
  342.     override func setSelected(_ selected: Bool, animated: Bool) {
  343.         super.setSelected(selected, animated: animated)
  344.  
  345.         // Configure the view for the selected state
  346.     }
  347.  
  348. }
Add Comment
Please, Sign In to add comment