TableView saving selected rows

0
class ViewController: UITableViewController {

    let dias = ["Segunda-feira","Terça-feira","Quarta-feira","Quinta-feira","Sexta-feira","Sábado","Domingo"]      

    var selecionados = [Bool]()

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dias.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = dias[indexPath.row]
        return cell
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        var selectedItem = indexPath
        if let cell = tableView.cellForRow(at: indexPath)
        {

        if tableView.cellForRow(at: indexPath)?.accessoryType == UITableViewCellAccessoryType.checkmark
        {
        tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.none
    }
        else{
            tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark
        }
        print(selectedItem.row)
}

I want to create a 'checkbox' I chose to do this through Tableview, however I have two difficulties, every time I select and unmark the line it's a print, I do not know if it's correct, however I wanted to add the selected lines in a variable and save with userDefaults, can anyone help me?

    
asked by anonymous 15.09.2017 / 21:53

1 answer

0

There are some options for you to do this, but an array of Bool I think will not help you ....

I think the best way is for you to have a dictionary [Day of the Week: Bool]. In your viewDidLoad, you initialize this dictionary by putting all values to false ... something like this:

for dia em dias {
  selecionados[dia] = false
}

In your didSelectRowAt function, if it was unchecked and the user checked, you make selecionados[dias[indexPath.row]] = true , otherwise you assign false again.

Now ... In this code sample, I'm not seeing UITableViewDelegate or UITableViewDataSource . Just check if in your project they are there. ;)

    
22.09.2017 / 00:06