我正在嘗試創建一個 TODO 串列應用程式。我正在將用戶輸入保存在 UserDefaults 中,并且它在我從主頁按鈕關閉應用程式時作業。但是當我從后臺應用程式中洗掉應用程式時,我之前洗掉的所有內容又回來了這里的一些代碼:code for delete row from tableView
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
items.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
在 GUI 上編輯的代碼
DispatchQueue.main.async {
self.items.append(text)
var currentEntry = UserDefaults.standard.stringArray(forKey: "items") ?? []
currentEntry.append(text)
UserDefaults.standard.setValue(currentEntry, forKey: "items")
self.tableView.reloadData()
}
uj5u.com熱心網友回復:
當您追加某些內容時,您將專案字串陣列保存到 UserDefaults,但是當您洗掉一個條目時,您不會將其保存到 UserDefaults。
如果您添加,您的代碼按預期對我有用
UserDefaults.standard.setValue(items, forKey: "items")
從 items 陣列中洗掉專案后。
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
items.remove(at: indexPath.row)
UserDefaults.standard.setValue(items, forKey: "items")
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
選擇
您將 didSet 添加到您的陣列中,以便在更改時將值保存到 UserDefaults,因此您不必每次都呼叫它:
var items = UserDefaults.standard.stringArray(forKey: "items") ?? [] {
didSet {
UserDefaults.standard.set(items, forKey: "items")
}
}
然后你可以做你的代碼來洗掉行:
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
items.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
添加專案時也不再需要手動保存它:
DispatchQueue.main.async {
self.items.append(text)
var currentEntry = UserDefaults.standard.stringArray(forKey: "items") ?? []
currentEntry.append(text)
self.tableView.reloadData()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/508525.html
下一篇:iOS藍牙執行長寫