Представление таблицы в представлении splitview, созданное с помощью источника данных, который нельзя удалить - PullRequest
1 голос
/ 07 апреля 2020

У меня есть контроллер табличного представления, который является основным в контроллере с разделенным представлением, использующим источники данных, которые можно использовать, и я пытаюсь выяснить проблему, с которой он не работает, с помощью свайпа для удаления параметров. Сначала я попытался использовать эту серию кода:

   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 {
            let context = fetchedResultsController.managedObjectContext
            context.delete(fetchedResultsController.object(at: indexPath))
            tableView.deleteRows(at: [indexPath], with: .fade)
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

Но это не дало никакого результата, вместо этого фактически проводя пальцем от мастера к детали. Затем я попытался использовать:

override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }

override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { (contextualAction, view, completionHandler) in
            guard let item = self.dataSource?.itemIdentifier(for: indexPath) else { return }
            self.container.viewContext.delete(item)
            self.setupSnapshot()
            completionHandler(true)
        }
        deleteAction.image = UIImage(systemName: "trash.fill")

        return UISwipeActionsConfiguration(actions: [deleteAction])
    }

Снова с тем же результатом, независимо от того, что я пробую, свайп просто производит перемещение к детали. Я получаю сообщение об ошибке при переходе к мастеру в своем приложении, которое гласит:

Warning once only: UITableView was told to layout its visible cells and other contents without being in the view hierarchy (the table view or one of its superviews has not been added to a window). This may cause bugs by forcing views inside the table view to load and perform layout without accurate information (e.g. table view bounds, trait collection, layout margins, safe area insets, etc), and will also cause unnecessary performance overhead due to extra layout passes.

Я не уверен, влияет ли это на то, что я делаю, или нет, или как это можно исправить. Может ли это быть проблема? Как мне позаботиться об этом? Приложение по-прежнему работает, но без функции салфетки для удаления. Я действительно чешу голову здесь.

...