2017-08-28 66 views
-1

我的代碼現在只列出了您手動輸入的內容。但是,當用戶切換視圖控制器時,代碼會消失。我試圖使用userdefualts將當前代碼保存在選擇函數中的行數中,但它不會將項保存在tableview單元格中。我只是想保存在tableview單元格中的任何東西。UITableViewCell中的UserDefaults未保存(swift3)

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) 


}} 
+0

當用戶切換視圖控制器時,代碼消失是什麼意思? 'numberOfRowsInSection'曾經被調用過嗎? – Ryan

+0

'items'的類型是什麼?如果它是一個自定義對象,則不能將它們存儲在'UserDefaults'中。 – Ryan

+0

@Ryan當用戶轉到主頁然後轉到列表頁面。所有寫在列表頁面上的東西在退貨時都不見了。 –

回答

1

你有一些問題在你的代碼:

  1. 你永遠不會從UserDefaults加載您的數據備份。 - 這是最大的
  2. 沒有必要撥打synchronise
  3. 您應該在添加/刪除數據時保存數據,而不是在numberOfRowsInSection

    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用於數據存儲:

  4. 如果插入新行,而不是重新加載整個表

我建議像它看起來更好這樣,但我認爲這只是一個簡單的學習練習。

+0

self.items = items = UserDefaults.standard.value(forKey:「items」)as? [字符串] ?? [String]()不編譯 –

+0

對不起,這是錯字。固定。 – Paulw11

+0

請考慮使用指定方法設置[set(_:forKey:)](https://developer.apple.com/documentation/foundation/userdefaults/1414067-set)並獲取[stringArray(forKey:)](https ://developer.apple.com/documentation/foundation/userdefaults/1416414-stringarray)。不要爲UserDefaults建議KVC。 – nayem