Swift-添加按钮操作后无法从TableView重新加载数据

问题描述 投票:0回答:1

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

我创建了一个带有自定义单元格的TableViewController。另外,我在导航栏中创建了一个“添加”按钮,以向表视图添加新值。将值保存在核心数据中,然后在viewWillAppear中获取它们。

当按下添加按钮时,UIAlertController会显示我已根据需要自定义的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)
        }
    }
}
ios swift tableview alert reloaddata
1个回答
1
投票

将群组项目添加到您的群组数组,然后重新加载表格视图,如下所示:-

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")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.