【问题标题】:How to get the current date using Date class in Swift如何在 Swift 中使用 Date 类获取当前日期
【发布时间】:2020-07-20 05:55:52
【问题描述】:

我正在使我的应用程序能够保存用户任务,现在我想将日期添加到表格视图中的副标题中。现在的问题是我不明白每次用户创建任务时如何获取当前日期,对于一些提示可能很酷,如果我违反任何 stackOverFlow 规则,我很抱歉:) 这是我的表格视图 VC 的代码:

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
    }
    
}

这是我的 tableview 的图片 - https://imgur.com/iFcr1iN

【问题讨论】:

  • 尽量减少您发布的代码量,以便理解您的问题。另外,如果您想知道任务的创建时间,为什么不在您的任务类型中添加日期属性?
  • @JoakimDanielson 它是我条目中的一个属性(我正在使用 CoreData),我要做的就是一旦用户将任务添加到列表中,副标题将显示任务已创建。
  • 您应该澄清您的问题,因为您需要在创建新任务实例时设置日期,然后在设置单元格标签时读取该属性
  • 如果您的Task 有一个日期属性(比如createdDate),那么您只需要newTask.createdDate=Date(),然后您使用DateFormatter 来获取您的日期的字符串表示形式cellForRow
  • 另外,请注意,一旦您的表格中的单元格超出屏幕大小,您在didSelectRowAt 中的选择/取消选择逻辑将不起作用,因为滚动时会重复使用单元格。您需要在数据模型中跟踪选中/取消选中状态。

标签: ios swift date tableview


【解决方案1】:

您可以使用 Date 类获取当前日期

  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
    }

如何使用字幕

cell.detailTextLabel?.text = getDate(date:Date())

【讨论】:

  • 问题是如何将它添加到字幕中? :)
  • 这里是如何做到这一点的......添加到detailTextLabel
  • ye 我已经试过了,问题是它更新了所有任务的日期:(
  • @Avi 你可以在Task中创建一个变量类型的日期来节省时间
  • @HHumorous 嗯,即使我会为日期创建一个全局变量并通过 CoreData 将其保存到我的条目中,每次我创建任务时,我都需要将字幕设置为该日期,这是不可能的
猜你喜欢
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-04
  • 2019-02-19
  • 2020-12-04
  • 1970-01-01
  • 2011-06-10
相关资源
最近更新 更多