Как добавить комментарии к различным UICells в UITableView - PullRequest
1 голос
/ 07 мая 2019

У меня есть UITableView с несколькими строками (каждая строка представляет вопрос), и когда я держу ячейку, я хочу добавить разные комментарии для каждой ячейки.У меня есть модель, где я жестко закодировал несколько вопросов.Проблема в том, что когда я добавляю комментарий, этот комментарий добавляется ко всем моим ячейкам.И я хочу добавить комментарий в соответствующую ячейку, но не для всех.Как я могу это сделать?

Я приложу здесь небольшой проект с моей проблемой: AppendCommentsToCells

Вот код для моей модели:

import Foundation

class ChecklistItemSection {

    var name: String // name of the section
    var checklistItems: [ChecklistItem] // all items from Checklist

    init(named: String, includeChecklistItems: [ChecklistItem]) {

        name = named
        checklistItems = includeChecklistItems
    }

    class func checklistItemSections() -> [ChecklistItemSection] {

        return [vehicleCheck(), viewingScreen(), batteryUnitAndFridge()]
    }

    // Private methods
    private class func vehicleCheck() -> ChecklistItemSection {

        var checklistItems = [ChecklistItem]()

        checklistItems.append(ChecklistItem(templateID: 1, lineID: 1, descript: "Question 1")!)
        checklistItems.append(ChecklistItem(templateID: 2, lineID: 2, descript: "Question 2")!)
        checklistItems.append(ChecklistItem(templateID: 3, lineID: 3, descript: "Question 3")!)

        return ChecklistItemSection(named: "Section 1", includeChecklistItems: checklistItems)
    }

    private class func viewingScreen() -> ChecklistItemSection {

        var checklistItems = [ChecklistItem]()

        checklistItems.append(ChecklistItem(templateID: 4, lineID: 4, descript: "Question 4")!)
        checklistItems.append(ChecklistItem(templateID: 5, lineID: 5, descript: "Question 5")!)
        return ChecklistItemSection(named: "Section 2", includeChecklistItems: checklistItems)
    }

    private class func batteryUnitAndFridge() -> ChecklistItemSection {

        var checklistItems = [ChecklistItem]()

        checklistItems.append(ChecklistItem(templateID: 6, lineID: 6, descript: "Question 6")!)
        checklistItems.append(ChecklistItem(templateID: 7, lineID: 7, descript: "Question 7")!)
        checklistItems.append(ChecklistItem(templateID: 8, lineID: 8, descript: "Question 8")!)
        checklistItems.append(ChecklistItem(templateID: 9, lineID: 9, descript: "Question 9")!)
        return ChecklistItemSection(named: "Section 3", includeChecklistItems: checklistItems)
    }
}


class ChecklistItem {

    var template_id: Int
    var line_id: Int
    var descript: String

    var vehicleComment: String = String()
    var trailerComment: String = String()

    init?(templateID: Int,
          lineID: Int,
          descript: String // Question name
        ) {

        self.template_id = templateID
        self.line_id = lineID
        self.descript = descript
    }
}

Вот мой ViewController:

import UIKit

class ChecklistVC: UIViewController {

    @IBOutlet weak var questionsTableView: UITableView!

    //Properties
    var vehicleCommentReceived = String()
    var trailerCommentReceived = String()
    lazy var itemSections: [ChecklistItemSection] = {
        return ChecklistItemSection.checklistItemSections()
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

    }
}

extension ChecklistVC: UITableViewDelegate, UITableViewDataSource {

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

        let itemCategory = itemSections[section]
        return itemCategory.checklistItems.count
    }

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

        return itemSections.count
    }

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "checklistCell", for: indexPath) as! ChecklistCell

        let itemCategory = itemSections[indexPath.section]
        let item = itemCategory.checklistItems[indexPath.row]
        cell.delegate = self
        cell.configCell(item)

        cell.vehicleCommentLabel.text = "Vehicle comment: \(vehicleCommentReceived)"

        cell.trailerCommentLabel.text = "Trailer comment: \(trailerCommentReceived)"

        return cell
    }

    // Set the header of each section
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

        let checklistItemCategory = itemSections[section]
        return checklistItemCategory.name.uppercased()
    }

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

        return 110
    }
}

extension ChecklistVC: ChecklistCellDelegate {

    func tapGestureOnCell() {

        showOptionsOnCellTapped()
    }

    func showOptionsOnCellTapped(){

        let addComment = UIAlertAction(title: "? Add Comment", style: .default) { action in
            self.performSegue(withIdentifier: "goChecklistAddComment", sender: nil)
        }

        let actionSheet = configureActionSheet()
        actionSheet.addAction(addComment)

        self.present(actionSheet, animated: true, completion: nil)
    }

    func configureActionSheet() -> UIAlertController {
        let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        actionSheet.addAction(cancel)

        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad ){
            actionSheet.popoverPresentationController?.sourceView = self.view
            actionSheet.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
            actionSheet.popoverPresentationController?.permittedArrowDirections = []
        }

        return actionSheet
    }
}

// Receive Comments using the Delegate
extension ChecklistVC: ChecklistAddCommentDelegate {

    func receiveVehicleComment(vehicleComment: String?, trailerComment: String?) {
        vehicleCommentReceived = vehicleComment ?? String()
        trailerCommentReceived = trailerComment ?? String()
        questionsTableView.reloadData()
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "goChecklistAddComment" {
            let addCommentVC = segue.destination as! ChecklistAddCommentVC
            addCommentVC.delegate = self
        }
    }
}

Здесь я прикрепил захват с моей проблемой:

enter image description here

Спасибо за вашвремя, если вы прочитаете это.

Ответы [ 2 ]

2 голосов
/ 07 мая 2019

2 переменные vehicleCommentReceived ,trailerCommentReceived должны быть свойствами в каждом объекте модели

class ChecklistItem {

   var template_id: Int
   var line_id: Int
   var descript: String

   var vehicleComment = "" //<<<<< here
   var trailerComment = ""  // <<<<< here

}

Когда вы редактируете ячейку, обязательно сохраняйте ее indexPath, а затем при сохранении изменяйте массив модели для данного раздела / строки indexPath


внутри ячейки

// Detect when the user press Long Tap on any cell
@objc func tapEdit(sender: UITapGestureRecognizer) {
    delegate?.tapGestureOnCell(self)
}

внутри vc объявите это

 var lastIndexPath:IndexPath!

и реализуйте как это

func tapGestureOnCell(_ cell:ChecklistCell) {

    showOptionsOnCellTapped(questionsTableView.indexPath(for: cell)!)
}

func showOptionsOnCellTapped(_ indexPath:IndexPath){

    let addComment = UIAlertAction(title: "? Add Comment", style: .default) { action in
        self.lastIndexPath = indexPath
        self.performSegue(withIdentifier: "goChecklistAddComment", sender: nil)
    }

    let actionSheet = configureActionSheet()
    actionSheet.addAction(addComment) 
    self.present(actionSheet, animated: true, completion: nil)
}

func receiveVehicleComment(vehicleComment: String?, trailerComment: String?) {
    let item = itemSections[lastIndexPath.section].checklistItems[lastIndexPath.row]
    item.vehicleComment = vehicleComment ?? ""
    item.trailerComment = trailerComment ?? ""
}

затем внутриcellForRowAt

cell.vehicleCommentLabel.text = "Vehicle comment: \(item.vehicleComment)" 
cell.trailerCommentLabel.text = "Trailer comment: \(item.trailerComment)"
0 голосов
/ 07 мая 2019

Вы сделали глобальную переменную для vehicleCommentReceived, trailerCommentReceived и отобразили их в cellForRowAtIndexPath.Что вам нужно сделать, это обновить вашу модель данных, т.е. этот конкретный объект (типа класса ChecklistItemSection) в массиве itemSections.

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