UITableViewCell 中的 UserDefaults 不保存 (swift3)

UserDefaults in a UITableViewCell not saving (swift3)

我的代码现在只列出您手动输入的内容。但是,当用户切换视图控制器时,代码就会消失。我尝试使用 userdefualts 将我当前的代码保存在选择函数的行数中,但它不会将项目保存在 tableview 单元格中。我只想保存 tableview 单元格中的任何内容。

import UIKit

class ViewController: UIViewController, UITableViewDataSource {

var items: [String] = [""]


@IBOutlet weak var listTableView: UITableView!
@IBAction func addItem(_ sender: AnyObject) {
    alert()
}

@IBOutlet weak var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    listTableView.dataSource = self



}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "listitem") as! ItemTableViewCell
    cell.itemLabel.text = items[indexPath.row]

    cell.preservesSuperviewLayoutMargins = false
    cell.separatorInset = UIEdgeInsets.zero
    cell.layoutMargins = UIEdgeInsets.zero




    return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let userDefaults = UserDefaults.standard

    userDefaults.setValue(items, forKey: "items")
    userDefaults.synchronize()
    return items.count



}
func alert(){
    let alert = UIAlertController(title: "", message: "", preferredStyle: .alert)
    alert.addTextField{
        (textfield) in
        textfield.placeholder = " Enter "

    }
    let add = UIAlertAction(title: "Add", style: .default){
        (action) in
        let textfield = alert.textFields![0] 

        self.items.append(textfield.text!)

        self.listTableView.reloadData()
    }
    let cancel = UIAlertAction(title: "Cancel", style: .cancel) {
        (alert) in


    }
    alert.addAction(add)
    alert.addAction(cancel)

    present(alert, animated: true, completion: nil)

}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    items.remove(at: indexPath.row)
    tableView.deleteRows(at: [indexPath], with: .automatic)


}}

您的代码中存在许多问题:

  1. 您永远不会从 UserDefaults 加载数据。 - 这是大的
  2. 不需要调用synchronise
  3. 当数据为 added/deleted 时,您应该保存数据,而不是 numberOfRowsInSection
  4. 插入一个新行而不是重新加载整个行看起来会更好table

我建议如下:

import UIKit

class ViewController: UIViewController, UITableViewDataSource {

    var items = [String]()

    @IBOutlet weak var listTableView: UITableView!
    @IBAction func addItem(_ sender: AnyObject) {
        alert()
    }

    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        listTableView.dataSource = self

        self.items = UserDefaults.standard.stringArray(forKey:"items")  ?? [String]()
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "listitem") as! ItemTableViewCell
        cell.itemLabel.text = items[indexPath.row]

        cell.preservesSuperviewLayoutMargins = false
        cell.separatorInset = UIEdgeInsets.zero
        cell.layoutMargins = UIEdgeInsets.zero

        return cell
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count    
    }

    func saveData() {
        userDefaults.standard.set(items, forKey: "items")
    }

    func alert(){
        let alert = UIAlertController(title: "", message: "", preferredStyle: .alert)
        alert.addTextField{
            (textfield) in
            textfield.placeholder = " Enter "

        }
        let add = UIAlertAction(title: "Add", style: .default){
            (action) in
            guard let textfield = alert.textFields?.first else {
                return
            }

            if let newText= textfield.text {
                self.items.append(newText)
                saveData()
                let indexPath = IndexPath(row: items.count - 1, section: 0)
                self.listTableView.insertRows(at: [indexPath], with: .automatic)
            }
        }

        let cancel = UIAlertAction(title: "Cancel", style: .cancel) {
            (alert) in

        }

        alert.addAction(add)
        alert.addAction(cancel)

        present(alert, animated: true, completion: nil)

    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        items.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .automatic)
        saveData()

    }
}

此外,您不应该真正使用 UserDefaults 以这种方式存储数据,但我认为这只是一个简单的学习练习。