【问题标题】:Swift - can't reload Data from TableView after add button actionSwift - 添加按钮操作后无法从 TableView 重新加载数据
【发布时间】:2020-05-15 11:31:28
【问题描述】:

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

我创建了一个带有自定义单元格的 TableViewController。 我还在导航栏中创建了一个“添加”按钮,为我的表格视图添加一个新值。 将值保存在 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)
        }
    }
}

【问题讨论】:

  • 在哪里将新插入的组添加到组中?
  • 我以为我在 addNewGroup 函数中创建了一个新的 NSManagedObject 并将其保存在核心数据中。数组组是所有保存的组对象的数组。当我切换 ViewController 并返回时,tableview 会显示新保存的组,因为 viewWillAppear 中的 reloadData 而不是当 addButtonAlert 被解除时。
  • 我尝试了一些方法并在addNewGroup 函数中编写了一个 if let 语句,现在 tableview 加载了它应该的值!但这是正确的处理方式吗? func addNewGroup(_:UIAlertAction) -&gt; Void { if let group = Groups(groupId: UUID(), groupTitle: groupsTextField!.text ?? "") { groups.append(group) do { try group.managedObjectContext?.save() groupsTableView.reloadData() ...
  • 是的。因为新项目不会简单地通过将其插入数据库来添加到称为组的数组中。组在 CoreData 之外。

标签: ios swift tableview alert reloaddata


【解决方案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")
    }
}

【讨论】:

    猜你喜欢
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    相关资源
    最近更新 更多