Сброс переупорядоченных строк TableView по нажатию кнопки - PullRequest
0 голосов
/ 06 июля 2018

Я реализую таблицу, в которой отображаются списки документов:

enter image description here

MyTableviewController

import UIKit

class MyTableViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    @IBOutlet weak var editButton: UIBarButtonItem!
    @IBOutlet weak var tableview: UITableView!

    var animalNameArray = ["cat","dog","lion"]

    override func viewDidLoad() {
        super.viewDidLoad()
        tableview.delegate = self
        tableview.dataSource = self
    }

    @IBAction func editButtonAtNavigationBar(_ sender: UIBarButtonItem) {
        self.tableview.isEditing = !self.tableview.isEditing
        sender.title = (self.tableview.isEditing) ?  "Done" : "Edit"
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let valueAtCell = tableView.dequeueReusableCell(withIdentifier: "myCustomCell", for: indexPath) as! CustomTableViewCell

        valueAtCell.cellLabel?.text = animalNameArray[indexPath.row]
        return valueAtCell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            animalNameArray.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.
        }
    }

    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    //Rearranging the table view cells

    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        let itemMove = animalNameArray[sourceIndexPath.row]
        animalNameArray.remove(at: sourceIndexPath.row)
        animalNameArray.insert(itemMove, at: destinationIndexPath.row)
     }
 }
  1. Я хочу сбросить упорядоченные списки, нажав кнопку отмены. Как?

  2. Когда я закрываю приложение и запускаю его снова (каждый раз, когда запускается функция обновления данных), строки возвращаются на свои места по умолчанию, в то время как мне нужно сохранить изменения в переупорядочении. enter image description here

А как я могу использовать изображение (мусор) в позиции удаления ??

Ответы [ 2 ]

0 голосов
/ 06 июля 2018
import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet weak var editButton: UIBarButtonItem!
    @IBOutlet weak var tableview: UITableView!

    var animalNameArray = [String]() {
        didSet {
            UserDefaults.standard.set(animalNameArray, forKey: "savedNameArray")
        }
    }
    var originalArray = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        tableview.delegate = self
        tableview.dataSource = self
        animalNameArray = UserDefaults.standard.array(forKey: "savedNameArray") as? [String] ?? ["cat","dog","lion"]
        originalArray = animalNameArray
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }

    @IBAction func editButtonAtNavigationBar(_ sender: UIBarButtonItem) {
        self.tableview.isEditing = !self.tableview.isEditing
        sender.title = (self.tableview.isEditing) ?  "Done" : "Edit"
    }

    @IBAction func cancelButtonAtNavigationBar(_ sender: UIBarButtonItem) {
        self.tableview.isEditing = false
        navigationItem.rightBarButtonItem?.title = "Edit"
        animalNameArray = originalArray
        tableview.reloadData()
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let valueAtCell = tableView.dequeueReusableCell(withIdentifier: "myCustomCell", for: indexPath) as! CustomTableViewCell

        valueAtCell.cellLabel?.text = animalNameArray[indexPath.row]
        return valueAtCell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            animalNameArray.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.
        }
    }

    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    //Rearranging the table view cells

    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        let itemMove = animalNameArray[sourceIndexPath.row]
        animalNameArray.remove(at: sourceIndexPath.row)
        animalNameArray.insert(itemMove, at: destinationIndexPath.row)
    }
}

Попробуйте этот код и подключите кнопку отмены из раскадровки к @IBAction func cancelButtonAtNavigationBar(_ sender: UIBarButtonItem)

0 голосов
/ 06 июля 2018

Вот решение

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet weak var editButton: UIBarButtonItem!
    @IBOutlet weak var tableview: UITableView!

    var animalNameArray = ["cat","dog","lion"]

    override func viewDidLoad() {
        super.viewDidLoad()
        tableview.delegate = self
        tableview.dataSource = self

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        let defaults = UserDefaults.standard
        let operationArray = defaults.stringArray(forKey: "SavedStringArray") ?? [String]()
        if operationArray.count == 0 {
        }else{
            animalNameArray = operationArray
        }

    }

    @IBAction func editButtonAtNavigationBar(_ sender: UIBarButtonItem) {
        self.tableview.isEditing = !self.tableview.isEditing
        sender.title = (self.tableview.isEditing) ?  "Done" : "Edit"
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let valueAtCell = tableView.dequeueReusableCell(withIdentifier: "myCustomCell", for: indexPath) as! CustomTableViewCell

        valueAtCell.cellLabel?.text = animalNameArray[indexPath.row]
        return valueAtCell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            animalNameArray.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
            print(animalNameArray)

            let defaults = UserDefaults.standard
            defaults.set(animalNameArray, forKey: "SavedStringArray")

        } 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.
        }
    }

    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    //Rearranging the table view cells

    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        let itemMove = animalNameArray[sourceIndexPath.row]
        animalNameArray.remove(at: sourceIndexPath.row)
        animalNameArray.insert(itemMove, at: destinationIndexPath.row)

        print(animalNameArray)
    }


}

Наслаждайтесь, ребята:)

Скачать образец

https://github.com/testingraahul/TableViewEditing/tree/master

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...