We are developing task applications using UserDefaults.
I want to implement the "All Deleted" feature, which removes all TableView contents, and I want to empty the saveList
of the variable that contains the array in the guard, but I don't know how to write it.
I'd like someone to teach me.
import UIKit
classHistoryViewController:UIViewController, UITableViewDelegate, UITableViewDataSource{
@IBOutlet weak var historyTableView: UITableView!
var saveArray: String = [ ]
vartextFieldValue: String=""
override func viewDidLoad(){
super.viewDidLoad()
title="History"
}
// From here
override func viewWillAppear(_animated:Bool){
super.viewWillAppear(animated)
guardlet saveList=UserDefaults.standard.array(forKey: "history") as?[String] else{
print("No Value"")
return
}
if saveArray==[]{
print(saveList)
// saveList=[] // I tried to put an empty array, but it didn't work.
}
saveArray=saveList.reversed()
self.historyTableView.reloadData()
}
@ IBAction func deleteButton(_sender:Any){
UserDefaults.standard.removeObject(forKey: "history")
I deleted the contents of saveArray.removeAll()//saveArray, but the tasks stored in saveList are displayed.
historyTableView.reloadData()
}
functableView(_tableView:UITableView, numberOfRowsInSection section:Int) - > Int{
// print(self.memoryArrayReversed.count)
// print(saveArray.count)
return saveArray.count
}
functableView(_tableView:UITableView, cellForRowAtindexPath:IndexPath) - >UITableViewCell{
letcell=historyTableView.dueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text=saveArray [indexPath.item]
// cell.textLabel?.numberOfLines=0
return cell
}
// Cell Removal Features
functableView(_tableView:UITableView, commit editingStyle:UITableViewCell.EditingStyle, forRowAtindexPath:IndexPath){
ifeditingStyle==UITableViewCell.EditingStyle.delete{
print(saveArray)
saveArray.remove(at:indexPath.row)
historyTableView.deleteRows(at:[indexPath as IndexPath], with:UITableView.RowAnimation.automatic)
// adding:saving deleted content
UserDefaults.standard.set(saveArray, forKey: "history")
}
}
}
I think it will work well by erasing about 8 lines from the guard and adding the following:
*I'm on the go, so I can't try it
self.saveArray=UserDefaults.standard.stringArray(forKey: "history")??[]
@cocona's code gives an error because saveList is defined in let and cannot be changed (empty).
© 2024 OneMinuteCode. All rights reserved.