简体   繁体   English

iOS Swift-删除tableViewCell中tableview中的行

[英]iOS Swift - Deleting row in tableview within a tableViewCell

So I was trying to delete items from a tableView inside a tableViewCell. 所以我试图从tableViewCell内部的tableView中删除项目。 The App is pretty much a ToDo List type of app where a user can add a task and then the tasks with the same dates can be grouped together. 该应用程序几乎是一种待办事项列表类型的应用程序,用户可以在其中添加任务,然后将具有相同日期的任务分组在一起。

The dates are in their own tableView, and within the cells of those dates include a tableView of the appropriate tasks that fall under them. 这些日期位于其自己的tableView中,并且在这些日期的单元格中包括位于其下的相应任务的tableView。

However, whenever I delete a task within a tableView in a tableViewCell, the app crashes. 但是,每当我删除tableViewCell中的tableView中的任务时,应用程序就会崩溃。

I have looked up the error that I receive whenever I delete a row but no changes. 我已经查询了删除行但没有更改时收到的错误。 And they are only for normal tableViews. 它们仅适用于普通的tableViews。 Not tableViews within a tableViewCell. 不是tableViewCell中的tableViews。

I have tried to add tableView.beginUpdates() and tableView.endUpdates() but problem still exists. 我试图添加tableView.beginUpdates()tableView.endUpdates()但问题仍然存在。 I am not sure what to go next in this as I thought this should work and I can't really find much about deleting rows in the tableView of a tableViewCell. 我不确定下一步该怎么做,因为我认为这应该起作用,而且我真的找不到在tableViewCell的tableView中删除行的很多方法。

The code is down below: 代码如下:

ToDoListTableViewController.swift (outer tableView) ToDoListTableViewController.swift(外部tableView)

class ToDoListTableViewController: UITableViewController {

    // MARK: - Properties
    var toDos = [ToDo]()
    var toDoDateGroup = [String]()
    var matchedToDoCount: Int = 0
    //var savedToDos = [ToDo]()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

        // If there are saved ToDos, load them
        if let savedToDos = loadToDos() {
            toDos = savedToDos
        }
        groupToDosAccordingToDates()
        sortToDoGroupDates()
    }

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

        //savedToDos = loadToDos()!

        groupToDosAccordingToDates()
        sortToDoGroupDates()
        reloadTableViewData()
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return toDoDateGroup.count
    }

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

        // Table view cells are reused and should be dequeued using a cell identifier.
        let dateCellIdentifier = "ToDoTableViewCell"
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "M/d/yy"
        //dateFormatter.dateFormat = "M/d/yy, h:mm a"

        guard let cell = tableView.dequeueReusableCell(withIdentifier: dateCellIdentifier, for: indexPath) as? ToDoTableViewCell else {
            fatalError("The dequeued cell is not an instance of ToDoTableViewCell.")
        }

        // Fetches the appropriate toDo for the data source layout.
        let toDoDate = toDoDateGroup[indexPath.row]

        cell.toDoDate = dateFormatter.date(from: toDoDate)!
        cell.toDoDateWeekDayLabel.text = toDoDate
        cell.toDoDateWeekDayLabel.backgroundColor = UIColor.green
        for toDo in toDos {
            //print(dateFormatter.string(from: toDo.workDate))
            //print("cell.ToDoDate Below:")
            //print(toDoDate)
            if dateFormatter.string(from: toDo.workDate) == toDoDate {
                cell.toDos.append(toDo)
            }
        }

        matchedToDoCount = cell.toDos.count
        //cell.toDoTableView.reloadData()

        return cell
    }

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

    // MARK: - Actions
    @IBAction func unwindToToDoList(sender: UIStoryboardSegue) {
        if let sourceViewController = sender.source as? ToDoItemTableViewController, let toDo = sourceViewController.toDo {

            if let selectedIndexPath = tableView.indexPathForSelectedRow {
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "M/d/yy"
                // Update an existing ToDo
                //toDos.append(toDo)
                toDoDateGroup[selectedIndexPath.row] = dateFormatter.string(from: toDo.workDate)
                tableView.reloadRows(at: [selectedIndexPath], with: .none)
            }

            else {
                // Add a new toDo
                toDos.append(toDo)

                var newIndexPath: IndexPath
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "M/d/yy"

                if (toDoDateGroup.isEmpty) {
                    newIndexPath = IndexPath(row: toDoDateGroup.count, section: 0)
                    toDoDateGroup.append(dateFormatter.string(from: toDo.workDate))
                    tableView.insertRows(at: [newIndexPath], with: .automatic)
                } else {
                    groupToDosAccordingToDates()
                }
            }

            // Save the ToDos
            saveToDos()
        }
    }


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


    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        super.prepare(for: segue, sender: sender)

        switch(segue.identifier ?? "") {
        case "AddToDoItem":
            os_log("Adding a new ToDo item.", log: OSLog.default, type: .debug)
        case "ShowToDoItemDetails":
            guard let toDoItemDetailViewController = segue.destination as? ToDoItemTableViewController else {
                fatalError("Unexpected destination: \(segue.destination)")
            }

            guard let selectedToDoItemCell = sender as? ToDoGroupTableViewCell else {
                fatalError("Unexpected sender: \(sender)")
            }

            guard let indexPath = tableView.indexPath(for: selectedToDoItemCell) else {
                fatalError("The selected cell is not being displayed by the table")
            }

            let selectedToDoItem = toDos[indexPath.row]
            toDoItemDetailViewController.toDo = selectedToDoItem
        default:
            fatalError("Unexpected Segue Identifier; \(segue.identifier)")
        }
    }

    // MARK: - Private Methods
    private func saveToDos() {
        //sortToDosByWorkDate()
        let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(toDos, toFile: ToDo.ArchiveURL.path)
        if isSuccessfulSave {
            os_log("ToDos successfully saved.", log: OSLog.default, type: .debug)
        } else {
            os_log("Failed to save toDos...", log: OSLog.default, type: .error)
        }
    }

    private func loadToDos() -> [ToDo]? {
        return NSKeyedUnarchiver.unarchiveObject(withFile: ToDo.ArchiveURL.path) as? [ToDo]
    }

    private func groupToDosAccordingToDates() {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "M/d/yy"
        //dateFormatter.dateFormat = "M/d/yy, h:mm a"

        var newIndexPath: IndexPath

        for toDo in toDos {
            print(toDo.taskName)
            let chosenWorkDate = dateFormatter.string(from: toDo.workDate)
            if !toDoDateGroup.contains(chosenWorkDate) {
                print(chosenWorkDate)
                newIndexPath = IndexPath(row: toDoDateGroup.count, section: 0)
                toDoDateGroup.append(chosenWorkDate)
                tableView.insertRows(at: [newIndexPath], with: .automatic)
            }
        }
    }

    private func sortToDoGroupDates() {
        toDoDateGroup = toDoDateGroup.sorted(by: {
            $1 > $0
        })
    }

    private func reloadTableViewData() {
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    }

}

ToDoTableViewCell.swift (inner tableView) ToDoTableViewCell.swift(内部tableView)

class ToDoTableViewCell: UITableViewCell, UITableViewDataSource, UITableViewDelegate {

    // MARK: - Properties

    @IBOutlet weak var toDoDateWeekDayLabel: UILabel!
    @IBOutlet weak var toDoTableView: UITableView!

    var toDos = [ToDo]()
    let dateFormatter = DateFormatter()
    var toDoDate = Date()

    let cellIdentifier = "ToDoGroupTableViewCell"

    override var intrinsicContentSize: CGSize {
        return self.intrinsicContentSize
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code

        dateFormatter.dateFormat = "M/d/yy, h:mm a"
        sortToDosByWorkDate()
        //reloadTableViewData()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
        toDoTableView.delegate = self
        toDoTableView.dataSource = self
    }

    // MARK: - Table view data source

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //print("Inner Cell Data");
        return toDos.count
    }

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

        let cellIdentifier = "ToDoGroupTableViewCell"
        let dueDateFormatter = DateFormatter()
        let workDateFormatter = DateFormatter()
        dueDateFormatter.dateFormat = "M/d/yy, h:mm a"
        workDateFormatter.dateFormat = "h:mm a"

        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? ToDoGroupTableViewCell  else {
            fatalError("The dequeued cell is not an instance of ToDoGroupTableViewCell.")
        }

        // Fetches the appropriate toDo for the data source layout.
        let toDo = toDos[indexPath.row]

        cell.taskNameLabel.text = toDo.taskName
        cell.workDateLabel.text = workDateFormatter.string(from: toDo.workDate)
        cell.estTimeLabel.text = toDo.estTime
        cell.dueDateLabel.text = dueDateFormatter.string(from: toDo.dueDate)

        return cell
    }

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

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source of the current tableViewCell
            let toDoToBeDeleted = toDos[indexPath.row]
            tableView.beginUpdates()
            toDos.remove(at: indexPath.row)
            saveToDos(toDoToBeDeleted: toDoToBeDeleted)
            tableView.deleteRows(at: [indexPath], with: .fade)
            tableView.endUpdates()
        } 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
        }
    }

    // MARK: - Private Methods

    private func saveToDos(toDoToBeDeleted: ToDo?) {
        // TODO: Refactor the deletion part of this function to be its own delete function
        // If there are existing toDos, load them
        if var savedToDos = loadToDos() {
            // If a there is a specific toDo to be deleted after save
            if toDoToBeDeleted != nil {
                print("toDoToBeDeleted is not nil")
                print(savedToDos)
                /*while let toDoIdToDelete = savedToDos.index(of: toDoToBeDeleted!) {
                    print("Index Exists in savedToDos")
                    savedToDos.remove(at: toDoIdToDelete)
                }*/
                savedToDos.removeAll{$0 == toDoToBeDeleted}
                let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(savedToDos, toFile: ToDo.ArchiveURL.path)
                if isSuccessfulSave {
                    os_log("A ToDo was deleted and ToDos is successfully saved.", log: OSLog.default, type: .debug)
                }
            // If there is no specific toDo to be deleted
            } else {
                let lastToDosItem: Int = toDos.count - 1
                savedToDos.append(toDos[lastToDosItem])
                let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(savedToDos, toFile: ToDo.ArchiveURL.path)
                if isSuccessfulSave {
                    os_log("A ToDo was added and ToDos is successfully saved.", log: OSLog.default, type: .debug)
                }
            }
        // If this is the initial save and no other toDos exists
        } else {
            let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(toDos, toFile: ToDo.ArchiveURL.path)
            if isSuccessfulSave {
                os_log("The initial ToDo is successfully saved.", log: OSLog.default, type: .debug)
            }
        }
    }

    private func loadToDos() -> [ToDo]? {
        print("loadToDos()")
        return NSKeyedUnarchiver.unarchiveObject(withFile: ToDo.ArchiveURL.path) as? [ToDo]
    }

    private func registerCell() {
        toDoTableView.register(ToDoTableViewCell.self, forCellReuseIdentifier: "ToDoTableViewCell")
    }

    private func sortToDosByWorkDate() {
        toDos = toDos.sorted(by: {
            $1.workDate > $0.workDate
        })
     }
}

Error output when deleting a row in the tableView within a tableViewCell: 在tableViewCell内的tableView中删除一行时输出错误:

2019-08-05 00:35:03.610047-0400 Focus-N-Do[1957:40199] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (5) must be equal to the number of rows contained in that section before the update (3), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
*** First throw call stack:
(
    0   CoreFoundation                      0x00000001095501bb __exceptionPreprocess + 331
    1   libobjc.A.dylib                     0x0000000107b66735 objc_exception_throw + 48
    2   CoreFoundation                      0x000000010954ff42 +[NSException raise:format:arguments:] + 98
    3   Foundation                          0x0000000107569877 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 194
    4   UIKitCore                           0x000000010c0e2e2d -[UITableView _endCellAnimationsWithContext:] + 18990
    5   UIKitCore                           0x000000010c0fc711 -[UITableView endUpdates] + 75
    6   Focus-N-Do                          0x00000001071201ac $S10Focus_N_Do02ToB13TableViewCellC05tableE0_6commit8forRowAtySo07UITableE0C_So0leF12EditingStyleV10Foundation9IndexPathVtF + 1036
    7   Focus-N-Do                          0x000000010712029b $S10Focus_N_Do02ToB13TableViewCellC05tableE0_6commit8forRowAtySo07UITableE0C_So0leF12EditingStyleV10Foundation9IndexPathVtFTo + 123
    8   UIKitCore                           0x000000010c120d90 __48-[UITableView _animateDeletionOfRowAtIndexPath:]_block_invoke + 71
    9   UIKitCore                           0x000000010c3b6235 +[UIView(Animation) performWithoutAnimation:] + 90
    10  UIKitCore                           0x000000010c120bdb -[UITableView _animateDeletionOfRowAtIndexPath:] + 219
    11  UIKitCore                           0x000000010c129739 __82-[UITableView _contextualActionForDeletingRowAtIndexPath:usingPresentationValues:]_block_invoke + 59
    12  UIKitCore                           0x000000010c07ef5e -[UIContextualAction executeHandlerWithView:completionHandler:] + 154
    13  UIKitCore                           0x000000010c084884 -[UISwipeOccurrence _performSwipeAction:inPullview:swipeInfo:] + 725
    14  UIKitCore                           0x000000010c086128 -[UISwipeOccurrence swipeActionPullView:tappedAction:] + 92
    15  UIKitCore                           0x000000010c08ad33 -[UISwipeActionPullView _tappedButton:] + 138
    16  UIKitCore                           0x000000010bedbecb -[UIApplication sendAction:to:from:forEvent:] + 83
    17  UIKitCore                           0x000000010b9170bd -[UIControl sendAction:to:forEvent:] + 67
    18  UIKitCore                           0x000000010b9173da -[UIControl _sendActionsForEvents:withEvent:] + 450
    19  UIKitCore                           0x000000010b91631e -[UIControl touchesEnded:withEvent:] + 583
    20  UIKitCore                           0x000000010bf170a4 -[UIWindow _sendTouchesForEvent:] + 2729
    21  UIKitCore                           0x000000010bf187a0 -[UIWindow sendEvent:] + 4080
    22  UIKitCore                           0x000000010bef6394 -[UIApplication sendEvent:] + 352
    23  UIKitCore                           0x000000010bfcb5a9 __dispatchPreprocessedEventFromEventQueue + 3054
    24  UIKitCore                           0x000000010bfce1cb __handleEventQueueInternal + 5948
    25  CoreFoundation                      0x00000001094b5721 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    26  CoreFoundation                      0x00000001094b4f93 __CFRunLoopDoSources0 + 243
    27  CoreFoundation                      0x00000001094af63f __CFRunLoopRun + 1263
    28  CoreFoundation                      0x00000001094aee11 CFRunLoopRunSpecific + 625
    29  GraphicsServices                    0x000000011166b1dd GSEventRunModal + 62
    30  UIKitCore                           0x000000010beda81d UIApplicationMain + 140
    31  Focus-N-Do                          0x00000001071230b7 main + 71
    32  libdyld.dylib                       0x000000010a9e9575 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

Any help would be greatly appreciated. 任何帮助将不胜感激。

The problem is not in beginUpdates , endUpdates etc. It's in ToDoTableViewCell logics. 问题不在beginUpdatesendUpdates等中,而是在ToDoTableViewCell逻辑中。

As the error text hints, you are deleting and/or inserting incorrect number of rows. 如错误提示所示,您正在删除和/或插入不正确的行数。

Consider this example: You delete 1 object from your data source (ie toDos ), you call tableView.deleteRows(at: [indexPath], with: .fade) for one indexPath . 考虑以下示例:从数据源(即toDos )中删除1个对象,为一个indexPath调用tableView.deleteRows(at: [indexPath], with: .fade)

Have that been the case, everything would be fine. 既然如此,一切都会好起来的。 But the error says that you had 3 rows before the update, now you have 5 rows after the update. 但是错误显示更新之前有3行,现在更新之后有5行。 And remember, you deleted 1 row, so you should be having 2 rows. 记住,您删除了1行,因此应该有2行。 How could this happen?.. App crashes. 这怎么可能发生?..应用程序崩溃。

The problem is that you are inserting objects to your data source somewhere, but are not calling tableView.inserRows(...) . 问题在于您正在将对象插入数据源中的某处,但没有调用tableView.inserRows(...) You need to figure this out. 您需要弄清楚这一点。

In your project you can use tableView datasource method canEditRowAt to delete the item from your tableView in the following manner : 在您的项目中,可以使用tableView数据源方法canEditRowAt通过以下方式从tableView中删除项目:

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete
        {
            toDos.remove(at: indexPath.row)
            tableView.reloadData()
        }
    }

Do remember to the reload the data in the tableView else the changes won't get reflected in tableView. 请记住要在tableView中重新加载数据,否则更改将不会反映在tableView中。

When deleting in commit editting method do not use begin or end updates if you want to use begin and end updates then perfrom deletion in editActionsForRowAt so do following 在提交编辑方法中删除时,如果要使用开始和结束更新,请不要使用开始或结束更新,然后在editActionsForRowAt进行perfrom删除, editActionsForRowAt执行以下操作

  func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
            if editingStyle == .delete {
                // Delete the row from the data source of the current tableViewCell
                let toDoToBeDeleted = toDos[indexPath.row]
                toDos.remove(at: indexPath.row)
                tableView.deleteRows(at: [indexPath], with: .fade)
                 saveToDos(toDoToBeDeleted: toDoToBeDeleted)

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

OR 要么

     func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

    let deleteAction = UITableViewRowAction(style: .destructive, title: "Delete") { (rowAction: UITableViewRowAction, indexPath: IndexPath) -> Void in
  let toDoToBeDeleted = toDos[indexPath.row]
                     tableView.beginUpdates()
                    toDos.remove(at: indexPath.row)
                    tableView.deleteRows(at: [indexPath], with: .fade)
                       tableView.endUpdates()
                     saveToDos(toDoToBeDeleted: toDoToBeDeleted)
    }
    return [deleteAction]
    }

And delete below part from commit editingStyle method 并从commit editStyle方法中删除以下部分

  let toDoToBeDeleted = toDos[indexPath.row]
        tableView.beginUpdates()
        toDos.remove(at: indexPath.row)
        saveToDos(toDoToBeDeleted: toDoToBeDeleted)
        tableView.deleteRows(at: [indexPath], with: .fade)
        tableView.endUpdates()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM