Tableview saving selected lines

Asked

Viewed 75 times

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)
}

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

1 answer

0

There are some options for you to do this, but an array of Bool I don’t think will 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 setting all values to false... something like that:

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

Already in your didSelectRowAt function, if it was unchecked and the user checked, you do selecionados[dias[indexPath.row]] = true, otherwise you assign falseagain.

Now... in this sample code, I’m not seeing UITableViewDelegate and neither UITableViewDataSource. Just make sure they’re there in your project. ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.