簡體   English   中英

Swift - 添加按鈕操作后無法從 TableView 重新加載數據

[英]Swift - can't reload Data from TableView after add button action

我是 Swift 的新手,需要您的幫助。

我創建了一個帶有自定義單元格的 TableViewController。 此外,我在導航欄中創建了一個“添加”按鈕,以向我的 tableview 添加一個新值。 將值保存在 Core Data 中並在 viewWillAppear 中獲取它們。

當按下添加按鈕時,一個 UIAlertController 會出現,我已經按照我的需要進行了自定義。 我添加了一個取消操作和一個確定操作,但是當我按下警報中的確定按鈕時,新值沒有出現在我的表格視圖中。 我必須切換到 tableview 顯示它的其他 viewcontroller。

我在代碼中的不同點添加了groupsTableView.reloadData()但無法讓它工作。

希望有人能幫幫我!

來自 MasterViewController 的代碼:

import UIKit
import CoreData

class MasterViewController: UITableViewController {

    var groups: [Groups] = []

    @IBOutlet weak var groupsTableView: UITableView!

    var groupsTextField: UITextField?


    override func viewDidLoad() {
        super.viewDidLoad()

        groupsTableView.delegate = self
        groupsTableView.dataSource = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

    override func viewWillAppear(_ animated: Bool) {

        // Core date initialization
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
            return
        }

        let managedContext = appDelegate.persistentContainer.viewContext

        let fetchRequest: NSFetchRequest<Groups> = Groups.fetchRequest()

        do {
            groups = try managedContext.fetch(fetchRequest)

            groupsTableView.reloadData()

        } catch {
            // TODO: error handling
            print("Could not fetch groups")
        }

        navigationItem.leftBarButtonItem = editButtonItem

        let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject))
        navigationItem.rightBarButtonItem = addButton
    }


    // MARK: - add new Group

    @objc func insertNewObject() {
        let addButtonAlert = UIAlertController(title: "Neue Gruppe", message: "Füge eine neue Gruppe deiner Liste hinzu", preferredStyle: .alert)
        addButtonAlert.addTextField { (UITextField) in
            self.groupsTextField = UITextField
            self.groupsTextField?.placeholder = "Name der Gruppe"
            self.groupsTextField?.clearButtonMode = .whileEditing
        }
        let okAction = UIAlertAction(title: "Hinzufügen", style: .default, handler: addNewGroup)
        let cancelAction = UIAlertAction(title: "Abbrechen", style: .cancel, handler: nil)

        addButtonAlert.addAction(okAction)
        addButtonAlert.addAction(cancelAction)

        self.present(addButtonAlert, animated: true, completion: nil)

    }

    func addNewGroup(_:UIAlertAction) -> Void {
        let group = Groups(groupId: UUID(), groupTitle: groupsTextField!.text ?? "")

        do {
            try group?.managedObjectContext?.save()

            groupsTableView.reloadData()

        } catch {
            // TODO: error handling
            print("Could not save group")
        }
    }

    // MARK: - Segue

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        guard let destination = segue.destination as? DetailViewController,
            let selectedRow = self.groupsTableView.indexPathForSelectedRow?.row else {
                return
        }
        destination.group = groups[selectedRow]
        destination.title = groups[selectedRow].groupTitle
    }

    // MARK: - delete Group

    func deleteGroup(at indexPath: IndexPath) {
        let group = groups[indexPath.row]

            guard let managedContext = group.managedObjectContext else {
                return
        }

        managedContext.delete(group)

        do {
            try managedContext.save()

            groups.remove(at: indexPath.row)

            groupsTableView.deleteRows(at: [indexPath], with: .automatic)
        } catch {
            //TODO: error handling
            print("Could not delete Group")

            groupsTableView.reloadRows(at: [indexPath], with: .automatic)
        }
    }

    // MARK: - Table View

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

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = groupsTableView.dequeueReusableCell(withIdentifier: "GroupsTableViewCell", for: indexPath)  as! GroupsTableViewCell
        let object = groups[indexPath.row]

        cell.groupTitleLabel?.text = object.groupTitle

        return cell
    }

    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            deleteGroup(at: indexPath)
        }
    }
}

將組項目添加到您的組數組,然后重新加載您的 tableview,如下所示:-

func addNewGroup(_:UIAlertAction) -> Void {
    let group = Groups(groupId: UUID(), groupTitle: groupsTextField!.text ?? "")
    do {
        try group?.managedObjectContext?.save()
        self.groups.append(group)
        groupsTableView.reloadData()
    } catch {
        // TODO: error handling
        print("Could not save group")
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM