Sunday, November 27, 2022
HomeiOS Developmentios - Swift5 Get the "invalid variety of rows in part" error...

ios – Swift5 Get the “invalid variety of rows in part” error when making an attempt to delete a row in tableview (activity supervisor with core knowledge)


Sirs! Making an attempt to create the Activity supervisor App with core knowledge. I’ve an array with all accomplished and present duties. I divide it for 2 arrays to load a tableview (it exhibits both present duties or duties are accomplished). Once I’m making an attempt to delete a activity with swipe on the desk, I obtain “invalid variety of rows in part” error. My code is under. Please advise methods to repair it? My thanks upfront.

import UIKit
import Basis

protocol TaskNotesDelegate: AnyObject {
    func refreshTasks()
    func deleteTask(with id: UUID)
}

class TasksViewController: UIViewController {
    
    @IBOutlet weak var doneTaskSwitcher: UIBarButtonItem!
    @IBOutlet weak var addTaskButton: UIBarButtonItem!
    static let identifier = "TasksViewController"
    let tableView: UITableView = {
        let tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        return tableView
    }()
    let idTasksCell = "idTasksCell"
    //константа для реализации функции поиска через searc controllr
    let searchController = UISearchController(searchResultsController: nil)
    var allTasks: [Task] = [] 
   
    var doneTasks: [Task] = []
    var currentTask: [Task] = []
    personal var filteredTasks: [Task] = []
    var currentSearch = ""
    var doneTasksCheck = false
    
    override func viewDidLoad() {
        tremendous.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.register(TaskTableViewCell.self, forCellReuseIdentifier: idTasksCell)
        configureSearchBar()
        setConstraints()
        fetchTasksFromStorage()
        
        for i in 0..<allTasks.rely {
            if allTasks[i].taskIsDone {
                doneTasks.append(allTasks[i])
            } else {
                currentTask.append(allTasks[i])
            }
        }
        
        for i in 0..<allTasks.rely {
            print("all (allTasks[i].id)")
        }
        
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.navigationBar.backgroundColor = .white
        self.tabBarController?.tabBar.backgroundColor = .white
        tableView.reloadData()
    }
    
    @IBAction func showDoneTasks(_ sender: UIBarButtonItem) {
        if doneTasksCheck == false {
            doneTasksCheck = true
            doneTaskSwitcher.title = "present"
            doneTasks = doneTasks.sorted { $0.taskDate > $1.taskDate }
            tableView.reloadData()
            addTaskButton.isEnabled = false
        } else {
            doneTasksCheck = false
            doneTaskSwitcher.title = "is finished"
            tableView.reloadData()
            addTaskButton.isEnabled = true
        }
    }
    
    personal func indexForTask(id: UUID, in listing: [Task]) -> IndexPath {
        let row = Int(listing.firstIndex(the place: { $0.id == id }) ?? 0)
        return IndexPath(row: row, part: 0)
    }
    
    @IBAction func addTaskButton(_ sender: UIBarButtonItem) {
        goToEditTask(createTask())
    }
    
    personal func goToEditTask(_ activity: Activity) {
        let controller = storyboard?.instantiateViewController(identifier: TaskDetailsViewController.identifier) as! TaskDetailsViewController
        controller.activity = activity
        controller.delegate = self
        navigationController?.pushViewController(controller, animated: true)
    }
    
    // MARK:- Strategies to implement
    personal func createTask() -> Activity {
        let activity = CoreDataManager.shared.createTask()
        
        // Replace desk
        allTasks.insert(activity, at: 0)
        tableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .computerized)
        return activity
    }
    
    personal func fetchTasksFromStorage() {
        allTasks = CoreDataManager.shared.fetchTasks()
    }
    
    personal func deleteTaskFromStorage(_ activity: Activity) {
        
        deleteTaskSviped(with: activity.id)
        CoreDataManager.shared.deleteTask(activity)
    }
    
}

//UITableViewDelegate, UITableViewDataSource
extension TasksViewController: UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection part: Int) -> Int {
        if doneTasksCheck == true {
            if currentSearch == "" {
                filteredTasks = doneTasks.sorted { $0.taskDate > $1.taskDate }
            }
        } else {
            if currentSearch == "" {
                filteredTasks = currentTask.sorted { $0.taskDate < $1.taskDate }
            }
        }
        return filteredTasks.rely
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: idTasksCell, for: indexPath) as! TaskTableViewCell
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd.MM.YYYY"
        cell.taskLabel.textual content = filteredTasks[indexPath.row].activity
        cell.taskDateLabel.textual content = dateFormatter.string(from: filteredTasks[indexPath.row].taskDate)
        if filteredTasks[indexPath.row].taskDate < Date().onlyDate! {
            cell.taskDateLabel.textColor = .pink
        } else {
            cell.taskDateLabel.textColor = .black
        }
        cell.taskTegLabel.textual content = filteredTasks[indexPath.row].taskTag
        if filteredTasks[indexPath.row].taskReminder != nil {
            cell.taskRemindTimeLabel.isHidden = false
            dateFormatter.dateFormat = "HH:mm"
            cell.taskRemindTimeLabel.textual content = dateFormatter.string(from: filteredTasks[indexPath.row].taskReminder!)
        } else {
            cell.taskRemindTimeLabel.isHidden = true
        }
        if filteredTasks[indexPath.row].taskNote == nil || filteredTasks[indexPath.row].taskNote == "" {
            cell.taskNoteLabel.isHidden = true
        } else {
            cell.taskNoteLabel.isHidden = false
        }
        if filteredTasks[indexPath.row].taskIsDone == false {
            cell.taskDoneButton.setBackgroundImage(UIImage(systemName: "circle"), for: .regular)
        } else {
            cell.taskDoneButton.setBackgroundImage(UIImage(systemName: "chevron.down.circle.fill"), for: .regular)
        }
        cell.layer.masksToBounds = true
        cell.layer.cornerRadius = 15
        cell.layer.borderWidth = 2
        cell.layer.borderColor = UIColor.white.cgColor
        cell.selectionStyle = .none
        cell.cellTaskDelegate = self
        cell.index = indexPath
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 75
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        goToEditTask(filteredTasks[indexPath.row])
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            deleteTaskFromStorage(filteredTasks[indexPath.row])
        }
    }
    
}

extension TasksViewController {
    
    func setConstraints() {
        view.addSubview(tableView)
        NSLayoutConstraint.activate([
            tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0),
            tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
            tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
            tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0)
        ])
    }
    
}

// MARK:- TaskNotes Delegate
extension TasksViewController: TaskNotesDelegate {
    
    func refreshTasks() {
        allTasks = allTasks.sorted { $0.taskDate < $1.taskDate }
        currentTask = currentTask.sorted { $0.taskDate < $1.taskDate }
        tableView.reloadData()
    }
    
    func deleteTaskSviped(with id: UUID) {
        let indexPath = indexForTask(id: id, in: filteredTasks)
        filteredTasks.take away(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .computerized)
        // simply in order that it does not come again once we search from the array
        allTasks.take away(at: indexForTask(id: id, in: allTasks).row)
    }
        
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments