Не удается получить данные из TableViewCell, так как didSelectRowAt не вызывается - PullRequest
0 голосов
/ 09 сентября 2018

У меня есть пользовательский UITableView, который содержит данные в каждой ячейке, которые я хочу извлечь и сохранить с помощью UserDefaults.

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

Проблема в том, что didSelectRowAt не вызывается, и я попробовал следующие методы:

  1. Обеспечение отсутствия распознавателей жестов«съедая» кран в ячейке (я никогда не добавлял распознаватель жестов).
  2. Установка части «Выбор» в Identity Inspector на «Нет» и «Единый выбор».

Вот скриншот того, как настроен ViewController с TableView:

Screenshot of Storyboard setup

Вот мой код:

class blueSide: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var items : [SosItem] = []
    @IBOutlet var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        tableView.delegate = self

        ref.observe(.value, with: {
            snapshot in
            var newItems : [SosItem] = []
            for child in snapshot.children {
                if let snapshot = child as? DataSnapshot,
                    let sosItem = SosItem(snapshot: snapshot) {
                    newItems.append(sosItem)
                }
            }
            self.items = newItems
            print(self.items)
            self.tableView.reloadData()
        })
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let removedItem = items.remove(at: indexPath.row)

            let itemsRef = ref.child(removedItem.key.lowercased())
            itemsRef.removeValue()
            tableView.reloadData()
        }
    }

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

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

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let sosItem = items[indexPath.row]
        print(sosItem)
        UserDefaults.standard.set(sosItem.clothingDescription, forKey: "clothingDescription")
        UserDefaults.standard.set(sosItem.placeName, forKey: "placeName")
        UserDefaults.standard.set(sosItem.longitude, forKey: "longitude")
        print("Longitude saved!")
        UserDefaults.standard.set(sosItem.latitude, forKey: "latitude")
        print("Latitude saved!")

        print(UserDefaults.standard.value(forKey: "latitude"))
        // tableView.deleteRows(at: [indexPath], with: .fade)
        //  tableView.reloadData()
        self.performSegue(withIdentifier: "uberSegue", sender: self)
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! CustomTableViewCell

        //get cell data from Firebase
        let sosItem = items[indexPath.row]
cell.descriptionLabel.text = sosItem.clothingDescription
        cell.latitudeLabel.text = String(sosItem.latitude)
        cell.longitudeLabel.text = String(sosItem.longitude)
        cell.locationNameLabel.text = sosItem.placeName
        cell.destinationLabel.text = sosItem.dropoffLocation

        return cell
    }

1 Ответ

0 голосов
/ 10 сентября 2018

Метод didSelectedRowAt не вызывается, когда tableView находится в режиме редактирования, свойство isEditing имеет значение true или вы вызываете canEditRowAt Попробуйте выбрать строку после завершения режима редактирования, как тест!

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