WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

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
    }

   

Hacking with Swift is sponsored by Emerge

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Find out more

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

Reply to this topic…

You need to create an account or log in to reply.

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.