Select row only 1 time

Viewed 51

I have tableView with channels for chat app. When user launches the app, I need to select a first channel as a default. At first I used willDisplay, and it worked, but now I decided to update color for unread channels (feature like unread messages). Every time when I call tableView.reloadData(), it's select first channel. selectRow doesn't work with willDisplay for some reasons.

let index = self.tableView.indexPathForSelectedRow
self.tableView.reloadData()
self.tableView.selectRow(at: index, animated: false, scrollPosition: .none)

.

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if indexPath.row == 0 {
        tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableView.ScrollPosition.none)
    }
}

How should I select first channel only 1 time when user launches the app?

1 Answers

You can try this with calling the didSelectRowAt method

var isSelected = false

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if indexPath.row == 0 && !isSelected  {
      tableView(tableView,didSelectRowAt: indexPath)
      isSelected = true
    }
}

Another option is to put this code inside viewWillAppear/viewDidAppear

if !isSelected {
    tableView.selectRow(at: IndexPath(row:0,section:0), animated: false, scrollPosition: UITableView.ScrollPosition.none)
    isSelected = true
}
Related