UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Deleting a single task from a table of structs

Forums > Swift

Hello, I'm completely new to Swift, and what I'm trying to make is a toDOList. It's not easy to explain, but the idea is that I select the name of the list from the picker, which appears in the textField and its index is passed to cellForRowAt, which makes these particular tasks display in the tableView. Unfortunately, when I delete a task from one list, it also reduces the number of rows in another list. Is there any simple way to preserve individual number of rows for every list? As next step I'd also like to remove the given list, add tasks to separate lists and modify the tasks. There's a lot of chaos in the code since I'm testing what particular things do, but after a few days I'm completely lost.

import UIKit

class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {

    @IBOutlet weak var AllTasksTableView: UITableView!
    @IBOutlet weak var textF: UITextField!
    @IBOutlet weak var listNo: UILabel!
    @IBOutlet weak var listBox: UITextField!
    @IBOutlet weak var listPicker: UIPickerView!
    var i1 = 0

    ///PICKER

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        var countRows = namesOfLists().count
        if pickerView == listPicker {
            countRows = self.namesOfLists().count
        }
        return countRows
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView == listPicker {
            let titleRow = namesOfLists()[row]

            if listBox.text != "" {
                let idx = tasksData.firstIndex(where: { $0.lista == listBox.text})!
                listNo.text = String(idx)
            }

            AllTasksTableView.reloadData()
            return titleRow
        }
        return ""

    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if pickerView == listPicker {
            self.listBox.text = self.namesOfLists()[row]
            //self.listPicker.isHidden = true
        }
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == self.listBox {
            //self.listPicker.isHidden = false
        }
    }

    @IBAction func delList(_ sender: Any) {
        if listBox.text != "" {
            tasksData.removeAll(where: { $0.lista == listBox.text})

        }
        AllTasksTableView.reloadData()

    }
    @IBAction func remove(_ sender: Any) {
        if listBox.text != "" {
            let idx = tasksData.firstIndex(where: { $0.lista == listBox.text})!
            listNo.text = String(idx)
        }

        AllTasksTableView.reloadData()
    }

    var task1: MyData!
    var tasksData = [MyData]()

    override func viewDidLoad() {
        super.viewDidLoad()
        AllTasksTableView.delegate = self
        AllTasksTableView.dataSource = self

        if task1 == nil {
        task1 = MyData(lista: "For friday", task: ["get a life", "find a friend"], completed: false)
        }

        tasksData.append(MyData.init(lista: "For today", task: ["Do homework", "Go to school"], completed: false))
        tasksData.append(MyData.init(lista: "For tomorrow", task: ["Relax", "Do nothing"], completed: false))
        tasksData.append(task1)

    }

    //TASKS NAMES
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell2 = AllTasksTableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as! AllTasksCell
        let num = Int(listNo.text ?? "0")!
        cell2.ATLabel.text = tasksData[num].task?[indexPath.row]

        cell2.checkBoxButton.isSelected = tasksData[indexPath.row].completed
        cell2.accessoryType = cell2.isSelected ? .checkmark : .none
        cell2.selectionStyle = .none // to prevent cells from being "highlighted"
        return cell2
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tasksData[section].task?.count ?? 0
        //return tasksData[section].task?.count ?? 0

    }

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

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
           // tableView.beginUpdates()
            tasksData[indexPath.section].task?.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)

            //tableView.endUpdates()
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark

   }

    func namesOfLists () -> [String] {
        let names = tasksData.map({$0.lista!})
        return names
    }

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.