-3

I'm making my app to be able to save the user tasks, now I would like to add the date to the subtitle in the tableview. now the problem is I don't get how can I get the current date every time the user creates a task, could be cool for some tips and sorry if I break any stackOverFlow rules :) Here's my code to the VC of my tableview:

import UIKit
import Foundation
import SwipeCellKit
import CoreData

//MARK: - Protocol to transfer the task Label to main VC:
protocol TaskDelegate {
    func updateTaskName(name:String)
}


//MARK: - Tasks View Controller:
class TasksViewController: UITableViewController, SwipeTableViewCellDelegate {
    
    


    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    
    
    var tasksArray = [Task]()
    var delegate: TaskDelegate?
    
    var taskName = ""
    
    override func viewDidLoad(){
        super.viewDidLoad()
        loadTasks()
        
        
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBar.prefersLargeTitles = true
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.navigationBar.prefersLargeTitles = false
    }
    
    
    

    // MARK: - Table view data source


    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return tasksArray.count
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "taskCell") as! SwipeTableViewCell
        
        cell.delegate = self
        cell.textLabel?.text = tasksArray[indexPath.row].title
        cell.imageView?.image = UIImage(named: "icon-unchecked-checkbox.png")
        cell.detailTextLabel?.text = ""
        
        return cell
    }

    
    // MARK: - Table view delegate methods:
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
        guard orientation == .right else { return nil }

        
        let deleteAction = SwipeAction(style: .destructive , title: .none) { action, indexPath in
            // handle action by updating model with deletion
            
            self.context.delete(self.tasksArray[indexPath.row])
            self.tasksArray.remove(at: indexPath.row)
            
            
            self.delegate?.updateTaskName(name: "")
            self.saveTasks()
            
        }

        let infoAction = SwipeAction(style: .default, title: .none) { action, indexPath in return }
        
        deleteAction.transitionDelegate = ScaleTransition.default
//        deleteAction.transitionDelegate = ScaleTransition.init(duration: 0.50, initialScale: 0.50, threshold: 0.50)
        infoAction.transitionDelegate = ScaleTransition.default
        


        // customize the action appearance
        
        deleteAction.image = UIImage(named: "icon-trash")
        infoAction.image = UIImage(named: "icon-more")

        

        return [deleteAction, infoAction]
    }
    
    
    
    // method to customize the behavior of the swipe actions(the delete action):
    func tableView(_ tableView: UITableView, editActionsOptionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeOptions {
        var options = SwipeOptions()
        options.expansionStyle = .destructive
        options.transitionStyle = .drag
        options.buttonSpacing = 10
        options.expansionDelegate = ScaleAndAlphaExpansion.init(duration:  0.15, scale:  0.5, interButtonDelay:  0.30)


        return options
    }
    
    
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       tableView.deselectRow(at: indexPath, animated: true)
        
        
        if tableView.cellForRow(at: indexPath)?.imageView?.image == UIImage(named: "icon-checked-checkbox.png") {
            let imageBox =  UIImage(named: "icon-unchecked-checkbox.png")

            tableView.cellForRow(at: indexPath)?.imageView?.image = imageBox
            
        } else {
            let imageBox = UIImage(named: "icon-checked-checkbox.png")
            tableView.cellForRow(at: indexPath)?.imageView?.image = imageBox
        }
    }
    
    
    
    
    // MARK: - Class Methods:
    //Adding task function:
    @IBAction func addPressedButton(_ sender: UIBarButtonItem) {
        var textField = UITextField()

        let alert = UIAlertController(title: "New Task", message: "Please insert a new task.", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

        alert.addTextField(configurationHandler: { alertTextField in
            alertTextField.placeholder = "Please insert your task"
            textField = alertTextField
        })

        
        
        
        
        alert.addAction(UIAlertAction(title: "OK", style: .destructive, handler: { action in
            //We Add the task into our array of Task objects once we reach into here:
            
            
            let newTask = Task(context: self.context)
            newTask.title = textField.text
            
            
            
            self.taskName = newTask.title!
            self.delegate?.updateTaskName(name: self.taskName)
            
            
            self.tasksArray.append(newTask)
            self.saveTasks()
            
            
            self.tableView.reloadData()
        }))

        self.present(alert, animated: true)
    }

    
    func getDate() -> String{
        let dateFormatter : DateFormatter = DateFormatter()
        //  dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        dateFormatter.dateFormat = "yyyy-MMM-dd HH:mm:ss"
        let date = Date()
        let dateString = dateFormatter.string(from: date)
        let interval = date.timeIntervalSince1970
        
        return dateString
    }
    
}

here's the picture of my tableview - https://i.stack.imgur.com/IpoSy.jpg

Avi Sabag
  • 61
  • 8
  • 1
    Try to minimise the amount of code you post to what is needed to understand your question. Also, why isn't date a property in you Task type if you want to know when the task was created? – Joakim Danielson Jul 20 '20 at 06:38
  • @JoakimDanielson it is a property in my entry(Im using CoreData), all I'm trying to do is once the user adds a task to the list, the subtitle will show the date of when the task was created. – Avi Sabag Jul 20 '20 at 07:11
  • You should clarify your question then because what you need is to set the date when creating a new Task instance and then read that attribute when setting the cell label – Joakim Danielson Jul 20 '20 at 08:35
  • If your `Task` has a date property (say `createdDate`) then all you need is `newTask.createdDate=Date()`, and then you use a `DateFormatter` to get the string representation of the date in your `cellForRow` – Paulw11 Jul 20 '20 at 09:23
  • Also, be aware that your selection/deselection logic in `didSelectRowAt` won't work once your table has more cells than fit on the screen as cells are re-used when you scroll. You need to track selected/deselected state in your data model. – Paulw11 Jul 20 '20 at 09:26
  • Does this answer your question? [How to get the current time as datetime](https://stackoverflow.com/questions/24070450/how-to-get-the-current-time-as-datetime) – Ryan Haycock Jul 20 '20 at 16:02

1 Answers1

0

You can get current date using Date class

  func getDate(date: Date) -> String{
        let dateFormatter : DateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MMM-dd HH:mm:ss"
        let dateString = dateFormatter.string(from: date)
        
        return dateString
    }

how to use subtitle

cell.detailTextLabel?.text = getDate(date:Date())
Jawad Ali
  • 13,556
  • 3
  • 32
  • 49