Reputation: 11
I tried to delete the rows by using the delete code but the row reappear everytime. I want to permanently delete any particular row.
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var countries = ["India","Canada", "USA","Russia","Dubai"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return countries.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = countries[indexPath.row]
return cell
}
//to enable delete action by swiping left
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete{
countries.remove(at: indexPath.row)
tableView.reloadData()
}
}
@IBOutlet weak var userTxt: UITextField!
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
let obj = UserDefaults.standard.object(forKey: "userKey") as? String
if let userName = obj {
userTxt.text = userName
}
}
@IBAction func savePressed(_ sender: UIButton) {
//we use this to save data
UserDefaults.standard.set(userTxt.text, forKey: "userKey")
}
@IBAction func deletePressed(_ sender: UIButton) {
UserDefaults.standard.removeObject(forKey: "userKey")
}
}
Upvotes: 0
Views: 504
Reputation: 144
Your implementation of delete does not persist the changes you make from delete as it uses a variable that’s initialized every time with data you hardcoded, hence array restores its elements to ones you specified every time you check back. So instead of hard coding values to an array to fill your tableView, consider using a persistent storage like a database or UserDefaults.
Upvotes: 0
Reputation: 16341
You have to save the modified array of countries to persist the changes you have made to it. Here's what you need to do:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//...
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
countries.remove(at: indexPath.row)
UserDefaults.standard.set(countries, forKey: "countries")
tableView.reloadData()
}
}
//...
override func viewDidLoad() {
super.viewDidLoad()
if let array = UserDefaults.standard.array(forKey: "countries") as? [String] {
countries = array
} else {
countries = ["India","Canada", "USA","Russia","Dubai"]
}
//...
}
}
Upvotes: 3