arraysswiftswift3checkmark

If checkmark is on - add object to the array [SWIFT]


Here is my code, but it doesn't saving user name into array

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // тут проверяем если ячейка уже выбрана то удаляем из массива и убираем чекмарк
    // если не выбрана то добавляем в массив и ставим чекмарк
    if tableView.cellForRow(at: indexPath)?.accessoryType == .checkmark {
        let cell = UITableViewCell()
        usersInGame.add(cell.textLabel?.text)
    } else {

        tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
    }
    tableView.deselectRow(at: indexPath, animated: false) //убираем выделение ячейки если не нужно обратное
    let usersInGame: NSMutableArray = []
}

I understood that it doesn't work, because when i turn on checkmark code doesn't work. Please help!


Solution

  • Look like you are creating a new cell and try to retrieve the text. Also, the local usersInGame is not needed as pointed out by @Samarth Kejriwal

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath), cell.accessoryType == .checkmark {
            usersInGame.add(cell.textLabel?.text)
        } else {
            tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
        }
        tableView.deselectRow(at: indexPath, animated: false)
    }
    

    Try this instead. Also, set a breakpoint to ensure that it go into usersInGame. Might have some syntax error, I am working on a laptop without XCode.