Search code examples
swiftxcodeuitableviewcore-datansuserdefaults

How to save checkmark in Swift?


I'm making a todo app for myself, and i wanted to make a function to mark a todo as done. It adds a checkmark and the font should become grey, but I'm new to coding so i dont really know how to save the font color and the checkmark to memory. I dont know if i sould save it to userdefaults or core data and most importantly how to save it. Any help is much appreciated.

Here is the code: I want to save the textColor and accesoryType

func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let done = UIContextualAction(style: .normal, title: "Done") { (action, view, nil) in
        print("Done")
        tableView.cellForRow(at: indexPath)?.textLabel?.textColor = UIColor.lightGray
       tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
    }
    done.backgroundColor = .blue
    let config = UISwipeActionsConfiguration(actions: [done])
    config.performsFirstActionWithFullSwipe = false
    return config           
}

Solution

  • In your data model add a property

    var isDone : Bool = false
    

    In cellForRow set the UI according to that property (assuming datasourceArray is the data source array)

    let item = datasourceArray[indexPath.row]
    cell.textColor = item.isDone ? .lightGray : .blue
    cell.accessoryType = item.isDone ? .checkmark : .none
    

    In the action set the isDone property to true and reload the row.

    let done = UIContextualAction(style: .normal, title: "Done") { (action, view, nil) in
        print("Done")
        self.datasourceArray[indexPath.row].isDone = true
        self.tableView.reloadRows(at: [indexPath], with: .none)
    }
    

    and delete

    done.backgroundColor = .blue