Ячейка Табличного представления действительно выбрала действие строки, основанное на выборе - PullRequest
0 голосов
/ 15 мая 2019

У меня есть несколько вопросов и ответов

вопросов в одном массиве и ответов в одном массиве.

Я хочу показать, когда пользователь выбирает вопрос, показать ответ снова, выбрать закрыть ответ.

Я пишу следующий код, но когда один ответ остается открытым, все закрыто, моя логика обратна любой помощи PLZ мне.

здесь я создал одну глобальную переменную с именем selectedindex

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "DonationTableViewCell", for: indexPath)as!
    DonationTableViewCell
    cell.questioncell.text = questnArr[indexPath.row]

    if indexPath.row  == selectedindex
    {
        cell.answerlbl.text = answersarr[indexPath.row]
        cell.questioncell.textColor = UIColor.disSatifyclr
        cell.questionimg.image = #imageLiteral(resourceName: "Drop down top icon")

    }else{
        cell.answerlbl.text = ""
        cell.questioncell.textColor = UIColor.textmaincolor
        cell.questionimg.image = #imageLiteral(resourceName: "Drop down")

    }
    tableviewheight.constant = tableview.contentSize.height

    return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    selectedindex = indexPath.row
    tableView.reloadData()
}

1 Ответ

1 голос
/ 15 мая 2019

Прежде всего объявите selectedindex как необязательный IndexPath

var selectedIndexPath : IndexPath?

в didSelectRowAt, вам необходимо выполнить несколько проверок:

  • Если selectedIndexPath == nil выберитестрока в indexPath
  • Если selectedIndexPath != nil и selectedIndexPath == indexPath отменить выбор строки в indexPath
  • Если selectedIndexPath != nil и selectedIndexPath != indexPath отменить выделение строки в selectedIndexPath и выбрать строкув indexPath.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if selectedIndexPath == nil {
        selectedIndexPath = indexPath
        tableView.reloadRows(at: [indexPath], with: .automatic)
    } else {
        if indexPath == selectedIndexPath! {
           selectedIndexPath = nil
           tableView.reloadRows(at: [indexPath], with: .automatic)
        } else {
           let currentIndexPath = selectedIndexPath!
           selectedIndexPath = indexPath
           tableView.reloadRows(at: [currentIndexPath, indexPath], with: .automatic)
        }
    }
}

В cellForRowAt проверка

if indexPath == selectedIndexPath
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...