Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- tableViewController.swift:
- import UIKit
- import os.log
- class TableViewController: UITableViewController {
- //temp list of tasks
- var tasks = [task]()
- override func viewDidLoad() {
- super.viewDidLoad()
- // Uncomment the following line to preserve selection between presentations
- // self.clearsSelectionOnViewWillAppear = false
- // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
- //self.navigationItem.leftBarButtonItem = self.editButtonItem
- //giving some default values in the cell
- //tasks += ["something"]
- loadSampleTasks()
- }
- // MARK: - Table view data source
- override func numberOfSections(in tableView: UITableView) -> Int {
- // #warning Incomplete implementation, return the number of sections
- return 1
- }
- override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- // #warning Incomplete implementation, return the number of rows
- return tasks.count
- }
- override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- let cell = tableView.dequeueReusableCell(withIdentifier: "simpleCell", for: indexPath)
- // Configure the cell...
- let row = indexPath.row
- cell.textLabel?.text = tasks[row].title
- //makes the cell background gray if its done
- if tasks[row].done {
- cell.backgroundColor = UIColor.lightGray
- }
- return cell
- }
- // Override to support conditional editing of the table view.
- override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
- // Return false if you do not want the specified item to be editable.
- return true
- }
- // Override to support editing the table view.
- override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
- if editingStyle == .delete {
- // Delete the row from the data source
- tasks.remove(at: indexPath.row)
- tableView.deleteRows(at: [indexPath], with: .fade)
- } else if editingStyle == .insert {
- // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
- }
- }
- //leading swipe for editing code
- override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
- let edit = UIContextualAction(style: .normal, title: "Edit") { (contextualAction, view, actionPerformed: (Bool) -> ()) in
- self.performSegue(withIdentifier: "showDetail", sender: UITableViewCell())
- actionPerformed(true)
- }
- return UISwipeActionsConfiguration(actions: [edit])
- }
- /*
- // Override to support rearranging the table view.
- override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
- }
- */
- /*
- // Override to support conditional rearranging of the table view.
- override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
- // Return false if you do not want the item to be re-orderable.
- return true
- }
- */
- // MARK: -Action
- @IBAction func unwindToTaskList(sender: UIStoryboardSegue) {
- if let sourceViewController = sender.source as? ViewController, let task = sourceViewController.Task {
- if let selectedIndexPath = tableView.indexPathForSelectedRow {
- // Update an existing task.
- tasks[selectedIndexPath.row] = task
- tableView.reloadRows(at: [selectedIndexPath], with: .none)
- }else {
- // Add a new meal.
- let newIndexPath = IndexPath(row: tasks.count, section: 0)
- tasks.append(task)
- tableView.insertRows(at: [newIndexPath], with: .automatic)
- }
- }
- }
- // MARK: - Navigation
- // In a storyboard-based application, you will often want to do a little preparation before navigation
- override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
- // Get the new view controller using segue.destination.
- // Pass the selected object to the new view controller.
- super.prepare(for: segue, sender: sender)
- switch(segue.identifier ?? "") {
- case "addItem":
- os_log("Adding a new task.", log: OSLog.default, type: .debug)
- case "showDetail":
- guard let ViewController = segue.destination as? ViewController else {
- fatalError("Unexpected destination: \(segue.destination)")
- }
- guard let selectedTaskCell = sender as? taskCellTableViewCell else {
- fatalError("Unexpected sender: \(sender)")
- }
- guard let indexPath = tableView.indexPath(for: selectedTaskCell) else {
- fatalError("The selected cell is not being displayed by the table")
- }
- let selectedTask = tasks[indexPath.row]
- ViewController.Task = selectedTask
- default:
- fatalError("Unexpected Segue Identifier; \(segue.identifier)")
- }
- }
- private func loadSampleTasks(){
- let formatter = DateFormatter()
- formatter.dateFormat = "MM/dd/yyyy"
- let date = formatter.date(from: "02/28/2020")
- guard let task1 = task(title: "call mom", done: false, date: date! )else{ fatalError("fuck you")}
- tasks += [task1]
- }
- }
- viewController aka the detail screen:
- import UIKit
- import os.log
- class ViewController: UIViewController, UITextFieldDelegate {
- @IBOutlet weak var taskTitleTextField: UITextField!
- @IBOutlet weak var taskLabel: UILabel!
- @IBOutlet weak var saveButton: UIBarButtonItem!
- @IBOutlet weak var doneSwitch: UISwitch!
- //code for the done button
- @IBAction func doneButton(_ sender: UIBarButtonItem){
- let isPresentingInAddMealMode = presentingViewController is UINavigationController
- if isPresentingInAddMealMode {
- dismiss(animated: true, completion: nil)
- }else if let owningNavigationController = navigationController{
- owningNavigationController.popViewController(animated: true)
- }else {
- fatalError("The MealViewController is not inside a navigation controller.")
- }
- }
- //gobal datePicker and toolbar for the date
- var toolBar = UIToolbar()
- var datePicker = UIDatePicker()
- var dateString : String = "" //holds the dateString for the button title
- @IBOutlet weak var titleHolder: UIButton!
- //shows the date picker when the button is pushed
- @IBAction func datePickerButton(_ sender: UIButton) {
- datePicker = UIDatePicker.init()
- datePicker.backgroundColor = UIColor.white
- datePicker.autoresizingMask = .flexibleWidth
- datePicker.datePickerMode = .date
- datePicker.addTarget(self, action: #selector(self.dateChanged(_:)), for: .valueChanged)
- datePicker.frame = CGRect(x: 0.0, y: UIScreen.main.bounds.size.height - 300, width: UIScreen.main.bounds.size.width, height: 300)
- self.view.addSubview(datePicker)
- toolBar = UIToolbar(frame: CGRect(x: 0, y: UIScreen.main.bounds.size.height - 300, width: UIScreen.main.bounds.size.width, height: 50))
- toolBar.isTranslucent = true
- toolBar.items = [UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.onDoneButtonClick))]
- toolBar.sizeToFit()
- self.view.addSubview(toolBar)
- //sets the button to the date
- //sender.setTitle(dateString, for: .normal)
- }
- //updates the due date
- @objc func dateChanged(_ sender: UIDatePicker?) {
- if let date = sender?.date {
- Task?.date = date
- dateString = dateToString(date: date)
- }
- }
- @objc func onDoneButtonClick() {
- toolBar.removeFromSuperview()
- datePicker.removeFromSuperview()
- titleHolder.setTitle(dateString, for: .normal)
- }
- //the task that gets sent back after saving
- var Task: task?
- override func viewDidLoad() {
- super.viewDidLoad()
- // Do any additional setup after loading the view.
- // Handle the text field’s user input through delegate callbacks.
- taskTitleTextField.delegate = self
- // Set up views if editing an existing task.
- if let Task = Task {
- navigationItem.title = Task.title
- taskTitleTextField.text = Task.title
- taskLabel.text = Task.title
- doneSwitch.isOn = Task.done
- titleHolder.setTitle(dateToString(date: Task.date), for: .normal)
- }
- // Enable the Save button only if the text field has a valid task title.
- updateSaveButtonState()
- }
- func textFieldShouldReturn(_ textField: UITextField) -> Bool {
- //hides the keyboard and stops the textField from being the first responder
- textField.resignFirstResponder()
- return true
- }
- func textFieldDidEndEditing(_ textField: UITextField) {
- taskLabel.text = textField.text
- updateSaveButtonState()
- navigationItem.title = textField.text
- }
- // This method lets you configure a view controller before it's presented.
- override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
- super.prepare(for: segue, sender: sender)
- guard let button = sender as? UIBarButtonItem, button === saveButton else {
- os_log("the save button was not pressed to get here, stopping", log: OSLog.default, type: .debug)
- return
- }
- let title = taskTitleTextField.text ?? ""
- let date = Task?.date ?? Date()
- let done = doneSwitch.isOn
- Task = task(title: title, done: done, date: date)
- }
- //MARK: Save Button
- //ensures new information was given when saving
- func textFieldDidBeginEditing(_ textField: UITextField) {
- // Disable the Save button while editing.
- saveButton.isEnabled = false
- }
- private func updateSaveButtonState() {
- // Disable the Save button if the text field is empty.
- let text = taskTitleTextField.text ?? ""
- saveButton.isEnabled = !text.isEmpty
- }
- //func for converting a date to a string
- func dateToString(date: Date) -> String{
- let formatter = DateFormatter()
- formatter.dateFormat = "MM/dd/yyyy"
- return formatter.string(from: date)
- }
- }
- tableViewCell.swift:
- import UIKit
- class taskCellTableViewCell: UITableViewCell {
- override func awakeFromNib() {
- super.awakeFromNib()
- // Initialization code
- }
- override func setSelected(_ selected: Bool, animated: Bool) {
- super.setSelected(selected, animated: animated)
- // Configure the view for the selected state
- }
- }
Add Comment
Please, Sign In to add comment