1

Задача в том - чтобы после нажатия на ячейку - я перехожу на другой экран, а когда я возвращаюсь обратно на этот экран нужно изменить цвет ячейки в таблице. Дабы дать понять пользователю, что он нажимал на эту ячейку ранее.

вот какие решения я пробовал, но не вышло:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var selectedCell:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
selectedCell.contentView.backgroundColor = UIColor.redColor()
}

// if tableView is set in attribute inspector with selection to multiple Selection it should work.

// Just set it back in deselect 

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    var cellToDeSelect:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
    cellToDeSelect.contentView.backgroundColor = colorForCellUnselected
}

И

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

/* this is where the magic happens, create a UIView and set its
   backgroundColor to what ever color you like then set the cell's
   selectedBackgroundView to your created View */

let backgroundView = UIView()
backgroundView.backgroundColor = YOUR_COLOR_HERE
cell.selectedBackgroundView = backgroundView
return cell

}

1
  • 1
    Вероятнее всего, когда вы возвращаетесь обратно на экран с таблицей, таблица обновляется. Вам надо сохранять индексы ранее нажатых ячеек. И потом проверять в методе cellForRowAtIndexPath рисовать эту ячейку как selected или же нет. 9 мар 2017 в 9:37

3 ответа 3

1

сделал костыль, рабочий, но хочется вариант по лучше конечно. Создал кастомную переменную содержащее массив интов static var selectedCell : [Int] = [] Затем в методе

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    Helpers.selectedCell.append(newsItem[indexPath.row].id)
}

по тапу на ячейку добавляю в статичный массив id новости

пробегаюсь по массиву с id'шками и сравниваю id текущее и id новости

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    for select in Helpers.selectedCell {
          if select == newsItem[indexPath.row].id {
              cell.contentView.backgroundColor = .red
          }
    }
}

и еще что не мало важно обновляю таблицу в viewwillAppear

1

вы можете воспользоваться протоколами, создать протокол в ячейке:

protocol CellDelegate {
    func cellDidTapped(using cell: CustomCell)
}

Так же создать в ячейке следующие var:

var cellDelegate: CellDelegate?
var isReaded = false

Далее в cellForRowAtIndexPath сделать следующее:

if cell.isReaded == true {
     cell.contentView.backgroundColor = UIColor.gray //(тут ваш цвет)
  }

В методе prepare(for segue: UIStoryboardSegue, sender: Any?) сделать что-то такое:

 guard let cell = sender as? CustomCell else {return}
 let destVC = segue.destination as? SecondViewController //ваш контроллер куда переходите
 cell.cellDelegate = destVC
 cell.cellDelegate?.cellDidTapped(using: cell)

Реализовать протокол в вашем SecondViewController, например так:

extension SecondViewController:CellDelegate{
    func cellDidTapped(using cell: CustomCell) {
        cell.isReaded = true
    }
}

И остается в методе tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) сделать например так:

let cell = self.tableView.cellForRow(at: indexPath) as? CustomCell
self.performSegue(withIdentifier: "show", sender: cell)

И в viewWillAppear обновлять таблицу: tableView.reloadData()

На мой взгляд достаточно приемлемо. Конечно метод протокола и все остальное можете поменять на свой вкус. Если остались не понятные моменты - жду пинга :)

З.Ы. Конечно стоит заменить CustomCell в протоколе просто на UITableViewCell и сделать приведение типов в конкретной реализации, а протокол вообще вынести в отдельный файл, тогда вы сможете реализовывать этот протокол в любом другом месте. А если обновление таблицы проблема, то можно обновлять конкретную ячейку.

1

Попробуйте создать свойство в Вашем кастомном классе ячейки isAlreadyVisited = false, в методе didSelectRow изменять это свойство на true, а в методе cellForRowAtIndexPath определять цвет ячейки в зависимости от от isAlreadyVisited:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomClass

 cell.contentView.backgroundColor = cell.isAlreadyVisited ?  color1 : color2 

}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.