DidSelectRowAtIndextPath дают мне неправильные данные - PullRequest
0 голосов
/ 21 ноября 2018

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

Любое объяснение, пожалуйста?

Мой код

Вот как я получаю данные

func getMyNotifications() {


Alamofire.request("\(Constant.GetMyNotifications)/-1", method: .get, encoding: JSONEncoding.default , headers: Constant.Header ).responseJSON { response in


    if let Json = response.result.value as? [String:Any] {


        if let ActionData = Json["ActionData"] as? [[String:Any]] {

            self.myNotifications = ActionData
            self.generalNotifications = ActionData
            //
            self.myNotificationsTV.reloadData()
            self.counter.text = "\(ActionData.count)"
            self.myNotifications.reverse()


            self.animationView.isHidden = true
            self.animationView.stop()
            self.refreshControl.endRefreshing()
        }
        if self.myBalaghat.count == 0 {

            self.myNotificationsTV.isHidden = true
            self.counter.text = "no notificatins to show"
        } else {
            self.myNotificationsTV.isHidden = false

        }
    }
}

}

Вот мой cellForRowAt

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if segmented.selectedSegmentIndex == 0 {

        return returnCell(balaghat: myNotificationsTV, withData: myNotifications, inCell: indexPath.row)
    }  else {

       return returnCell(balaghat: myNotificationsTV, withData: allNotifications, inCell: indexPath.row)
    }

}

Мой didSelectRowAt

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

    generalNotifications.reverse()
    let prepareNum = generalNotifications[indexPath.row]["Id"] as? NSNumber

    currentBalaghId = Int(prepareNum!)
    clickedIndex = indexPath.row
    if let text = generalNotifications[indexPath.row]["NotifDateG"] as? String {
        prepareDateforPassing = text
    }

    if let text = generalNotifications[indexPath.row]["Description"] as? String {
        prepareDesciptionforPassing = text 
    }

    if let text = generalNotifications[indexPath.row]["TypeName"] as? String {
       prepareTypeforPassing = text
   }

   if let text = generalNotifications[indexPath.row]["AddedByName"] as? String {

        prepareProviderNameforPassing = text
   }


    self.performSegue(withIdentifier: "showDetails", sender: self)
    // to remove highlighting after finish selecting
    tableView.deselectRow(at: indexPath, animated: true)
}

1 Ответ

0 голосов
/ 21 ноября 2018

Похоже, вы делаете обратное в своем массиве myNotifications после вызова reViewData tableView.Поэтому попробуйте перезагрузить tableView, как только вы перевернули массив myNotifications, как показано ниже.

   if let ActionData = Json["ActionData"] as? [[String:Any]] {

        self.myNotifications = ActionData
        self.generalNotifications = ActionData
        //
        self.counter.text = "\(ActionData.count)"
        self.myNotifications.reverse()
        self.myNotificationsTV.reloadData()


        self.animationView.isHidden = true
        self.animationView.stop()
        self.refreshControl.endRefreshing()
    }

Также вы заметили, что вы делаете реверс в своем массиве (generalNotifications.reverse()) всякий раз, когда выбираете ячейку, котораябудет переворачивать ваш массив каждый раз.Итак, в первый раз вы получите правильное значение, а в следующий раз массив будет перевернут, и будет возвращено неправильное значение.Попробуйте использовать обратный массив, как показано ниже.

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

    let reversedGeneralNotifications = generalNotifications.reversed()
    let prepareNum = reversedGeneralNotifications[indexPath.row]["Id"] as? NSNumber

    currentBalaghId = Int(prepareNum!)
    clickedIndex = indexPath.row
    if let text = reversedGeneralNotifications[indexPath.row]["NotifDateG"] as? String {
        prepareDateforPassing = text
    }

    if let text = reversedGeneralNotifications[indexPath.row]["Description"] as? String {
        prepareDesciptionforPassing = text 
    }

    if let text = reversedGeneralNotifications[indexPath.row]["TypeName"] as? String {
       prepareTypeforPassing = text
   }

   if let text = reversedGeneralNotifications[indexPath.row]["AddedByName"] as? String {

        prepareProviderNameforPassing = text
   }


    self.performSegue(withIdentifier: "showDetails", sender: self)
    // to remove highlighting after finish selecting
    tableView.deselectRow(at: indexPath, animated: true)
}
...