Кнопка Tableview Like создает копию, когда прослушиватель снимков вступает в силу - PullRequest
0 голосов
/ 19 апреля 2020

так что в основном, когда нажимается кнопка «Нравится», предполагается, что она изменяет количество лайков в табличном представлении, но в результате получается дублирующаяся ячейка в нижней части массива табличного представления, и это с новым числом лайков, поэтому я делаю что-то неправильно, но я не уверен, что, если есть лучший способ сделать это, пожалуйста, я бы оценил его, показанный мне

import UIKit
import Firebase
 class motivationviewcontroller : UIViewController,UITableViewDataSource ,UITableViewDelegate{


var motivationThoughts = [motivationDailyModel]()
var Mous = motivationDailyModel()
var tableview : UITableView!

override func viewDidLoad() {

    print("the user logged in is \( String(describing: Auth.auth().currentUser?.email))")

    tableview =  UITableView(frame: view.bounds, style: .plain)
           tableview.backgroundColor = UIColor.white
           view.addSubview(tableview)


    var layoutGuide : UILayoutGuide!
    layoutGuide = view.safeAreaLayoutGuide

    let cellNib = UINib(nibName: "dailyMotivationTableViewCell", bundle: nil)
    tableview.register(cellNib, forCellReuseIdentifier: "DailyThoughtCELL")
    tableview.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
    tableview.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
    tableview.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
    tableview.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true


    tableview.dataSource = self
    tableview.delegate = self


   loaddailymotivation()
                //listener()
    self.tableview.reloadData()


}

override func viewDidAppear(_ animated: Bool) {
  //loaddailymotivation()
    self.tableview.reloadData()


}



//======================================================================


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

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

        cell!.generateCellsforDailymotivation(_MotivationdataMODEL: self.motivationThoughts[indexPath.row])
        return cell!
   }



func loaddailymotivation() {
    FirebaseReferece(.MotivationDAILY).addSnapshotListener { querySnapshot, error in

        guard let snapshot = querySnapshot else {
            print("Error fetching snapshots: \(error!)")
            return
        }

        snapshot.documentChanges.forEach { diff in
            if (diff.type == .added) { // this line means if the chage that happened in the document was equal to added something

                let data = diff.document.data()
                  print("we have\(snapshot.documents.count) documents in this array")

                  let dailyMotivationID = data["objectID"] as! String

                  let dailymotivationTitle = data["Motivation title"] as! String //calls the data thats heald inside of motivation title in firebase
                  let dailyMotivationScripture = data["daily motivation scripture"] as! String //calls the data thats heald inside of Motivation script in firebase

                  let dailyMotivationNumberOfLikes = data["Number of likes in daily motivation post"]as! Int



                 let MdataModel = motivationDailyModel(RealMotivationID: dailyMotivationID, RealmotivationTitle: dailymotivationTitle, RealmotivationScrip: dailyMotivationScripture, RealmotivationNumberOfLikes: dailyMotivationNumberOfLikes)

                self.motivationThoughts.append(MdataModel)

            }
            //===== //=====
            if (diff.type == .modified) {
                print("Modified data: \(diff.document.data())")

                 let newdata = diff.document.data()

                 let dailyMotivationID = newdata["objectID"] as! String

                 let dailymotivationTitle = newdata["Motivation title"] as! String //calls the data thats heald inside of motivation title in firebase
                 let dailyMotivationScripture = newdata["daily motivation scripture"] as! String //calls the data thats heald inside of Motivation script in firebase

                let dailyMotivationNumberOfLikes = newdata["Number of likes in daily motivation post"]as! Int


                let MdataModel = motivationDailyModel(RealMotivationID: dailyMotivationID, RealmotivationTitle: dailymotivationTitle, RealmotivationScrip: dailyMotivationScripture, RealmotivationNumberOfLikes: dailyMotivationNumberOfLikes)


                self.motivationThoughts.append(MdataModel)

                //  here you will receive if any change happens in your data add it to your array as you want
            }

            DispatchQueue.main.async {

                self.tableview.reloadData()
            }

        }
    }
}

1 Ответ

0 голосов
/ 19 апреля 2020

Я не знаю, будет ли loaddailymotivation() вызываться снова после viewDidLoad, но в этом методе вы делаете self.motivationThoughts.append(MdataModel), что должно точно соответствовать тому, что вы сказали, что он делает.

Я думаю, вам нужен метод, который идентифицирует элемент, который необходимо изменить в массиве, и заменяет / модифицирует его. Если вы добавляете новый объект, у вас есть еще один элемент в вашей таблице

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