Добавить выбранные ячейки в виде таблицы в другой раздел - PullRequest
0 голосов
/ 19 марта 2019

У меня есть несколько строк, отображаемых в виде таблицы, например ... enter image description here

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

enter image description here

При нажатии на кнопку-флажок я пробовал что-то подобное ...

  func productTap(cell: ProductTagTableViewCell) {
    if let indexPath = tableview?.indexPath(for: cell) {
      print("indexPath.row: \(indexPath.row)")

  let prodItem = self.arrData[indexPath.row]
  selectedItems.append(prodItem)
  self.tableview.beginUpdates()

  // Creating indexpath for the new item
  let indexPath = IndexPath(row: selectedItems.count - 1, section: 0)
  tableview.insertRows(at: [indexPath], with: .automatic)
  tableview.endUpdates()

  }
}

Но вылетает только с ошибкой ..

Завершение приложения из-за необработанного исключения «NSInternalInconsistencyException», причина: «Неверное обновление: недопустимое количество строк в разделе 0. Число строк, содержащихся в существующем разделе после обновления (3), должно быть равно количеству строк». содержится в этом разделе до обновления (3), ....

РЕДАКТИРОВАТЬ 1: Вот так выглядит моя модель ..

class NewModel {
  var heading : String
  var subHeading : String
  var selected = false

  init(heading : String, subHeading : String) {
    self.heading = heading
    self.subHeading = subHeading

  }

  class func getModelData() -> [NewModel] {

    let array = [NewModel(heading: “This is heading1“, subHeading: "This is sub heading1"),
                 NewModel(heading: "This is heading2”, subHeading: "This is sub heading2”),
                 NewModel(heading: "This is heading3”, subHeading: "This is sub heading3”)]

    return array
  }
}

РЕДАКТИРОВАТЬ 2 Новые изменения:

Это мои методы делегата табличного представления:

 func numberOfSections(in tableView: UITableView) -> Int {
    return 2
  }

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    var count: Int?
    if section == 0 {
      count = self.arrData2.count
    }
    else if section == 1 {
      return self.arrData.count
    }
    return count!
  }

  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 93.0
  }

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

    let cell: ProductTagTableViewCell = tableView.dequeueReusableCell(withIdentifier: cellID) as! ProductTagTableViewCell
    cell.delegate = self
    cell.selectionStyle = .none

    switch (indexPath.section) {
    case 0:
      cell.productNameLabel.text = self.arrData2[indexPath.row].heading
      cell.priceLabel.text = self.arrData2[indexPath.row].subHeading

    case 1:
      cell.productNameLabel.text = self.arrData[indexPath.row].heading
      cell.priceLabel.text = self.arrData[indexPath.row].subHeading

    default:
      cell.productNameLabel.text = self.arrData[indexPath.row].heading
      cell.priceLabel.text = self.arrData[indexPath.row].subHeading

    }
    return cell
  }

По нажатию кнопки-флажка я сделал это ...

func productTap(cell: ProductTagTableViewCell) {
    if let indexPath = tableview?.indexPath(for: cell) {

      self.arrData2.append(self.arrData[indexPath.row])
      self.arrData.remove(at: indexPath.row)
      tableview.deleteRows(at: [indexPath], with: .automatic)
      tableview.beginUpdates()
      tableview.insertRows(at: [IndexPath(row: arrData2.count-1, section: 0)], with: .automatic)
      self.tableview.endUpdates()
   }
}

1 Ответ

0 голосов
/ 19 марта 2019

Пожалуйста, используйте более значимые имена переменных.arrData и arrData2 ужасны и запутаны.

Назовите массивы, например,

var deselectedProducts = [NewModel]()
var selectedProducts = [NewModel]()

Чтобы переместить элемент из deselected в selected, напишите

func productTap(cell: ProductTagTableViewCell) {
    if let indexPath = tableview?.indexPath(for: cell) {
       let itemToMove = deselectedProducts.remove(at: indexPath.row) 
       let insertionIndexPath = IndexPath(row: selectedProducts.count, section: 0)
       selectedProducts.append(itemToMove)
       tableview.beginUpdates()
       tableview!.deleteRows(at: [indexPath], with: .automatic)
       tableview!.insertRows(at: [insertionIndexPath], with: .automatic)
       self.tableview.endUpdates()
   }
}

Кстати, вы можете уменьшить код в numberOfRowsInSection до

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
    return (section == 0) ? selectedProducts.count : deselectedProducts.count
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...