如何使用UserDefault将两个值相加

时间:2019-03-03 11:53:28

标签: swift

我正在尝试在Swift中制作一个简单的ToDo应用。

我不仅要添加任务,而且要添加Date, 但我不知道如何将两个值添加到变量中。

我想添加一个从UIDatePickerTodoAdded的文本。

请给我任何建议吗?

import UIKit

//Variable
var TodoAdded = [String]()

class AddController: UIViewController {

    //TextField
    @IBOutlet weak var TodoTextField: UITextField!

    //TextField for Date
    @IBOutlet weak var DateTextField: UITextField!
    var datePicker: UIDatePicker = UIDatePicker()

    //追加ボタンの設定
    @IBAction func TodoAddButten(_ sender: Any) {
        //Add typed text to variable
        TodoAdded.append(TodoTextField.text!)
        //Empty after tapped button
        TodoTextField.text = ""
        //Add to UD
        UserDefaults.standard.set( TodoAdded, forKey: "TodoList" )
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Picker Setting
        datePicker.datePickerMode = UIDatePicker.Mode.dateAndTime
        datePicker.timeZone = NSTimeZone.local
        datePicker.locale = Locale.current
        DateTextField.inputView = datePicker

        // 
        let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 35))
        let spacelItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
        let doneItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(done))
        toolbar.setItems([spacelItem, doneItem], animated: true)

        // InputView
        DateTextField.inputView = datePicker
        DateTextField.inputAccessoryView = toolbar
    }

    // 
    @objc func done() {
        DateTextField.endEditing(true)

        // Format 
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        DateTextField.text = "\(formatter.string(from: Date()))"
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

1 个答案:

答案 0 :(得分:1)

您可以尝试将其另存为[String:[String]]

UserDefaults.standard.set([dateTextField.text!:todoAdded], forKey: "TodoList" )

一个好的方法是

struct Root:Codable {
    let date:Date
    let tasks:[String]
}

然后使用JSONDecoder / JSONEncoder转换为对象/数据,之后您可以轻松地保存/读取它们