** Так что я пытаюсь добавить изменение метки количества лайков в ячейку табличного представления, я просто пытаюсь добавить 1 к нему, и я не уверен, как именно я могу это сделать, я уже написал код, который добавляет 1, как когда подобное в firebase нажата кнопка. Я просто хочу показать, что в ячейке табличного представления в любом случае есть возможность добавить единицу к значению, в котором уже содержится код, который я написал
, например: у меня 200 лайков нажата кнопка «Мне нравится». Я хочу обновить метку ячейки и показать 201 «лайков». Я вижу, что изменения произошли в моей базе данных пожарного магазина, но я хочу, чтобы она показала **
import UIKit
import FBSDKLoginKit
import Firebase
import JGProgressHUD
class dailyMotivationTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
//numberOfLikesGenerator()
self.holdView.layer.cornerRadius = 19
self.likedbuttonFIlled.isHidden = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
//MARK: IBOUTLETS
@IBOutlet weak var holdView: UIView!
@IBOutlet weak var likedbuttonFIlled: UIImageView!
@IBOutlet weak var likeSavedButton: UIButton!
@IBOutlet weak var DMtextLabel: UILabel!
@IBOutlet weak var DMtitleLabel: UILabel!
@IBOutlet weak var numberOfLikesLabel: UILabel!
//MARK: VARS/LETS
let hud = JGProgressHUD(style: .light)
//MARK: IBACTIONS
@IBAction func likeButtonTapped(_ sender: Any) {
if (Auth.auth().currentUser != nil || AccessToken.current != nil) {
changeLikeButtonMode()
//update like number and update like number on firebase
}
else{
hud.textLabel.text = "Please Login to Continue!"
hud.show(in: self.contentView)
hud.dismiss(afterDelay: 3.0)
hud.indicatorView = JGProgressHUDErrorIndicatorView()
//no user login so pull up login view
}
//MARK: TODO when this button is tapped ALSO WANT TO STORE THIS SNAPSHOT INTO AN ARRAY THAT WE WILL SHOW IN OUR SAVED VIEW CONTROLLEr
}
func incrementLikes(){
FirebaseReferece(.MotivationDAILY).document("540C208A-A9A0-465C-BE20-C7010D114F75").updateData(["Number of likes in daily motivation post":FieldValue.increment(Int64(1))]) { (error) in
if error != nil {
print(error!.localizedDescription)
} else {
print("successfully incremented data!")
}
}
}
func changeLikeButtonMode(){
// so if likedbutton is tapped and the heart isnt red that means that the tag is = 0 so its gnna show the red heard and then also change the tag to 1 but when it is tapped again its going to change the tag to 0 and removed the red heart
if likeSavedButton.tag == 0 //means its empty
{
incrementLikes()
self.likedbuttonFIlled.isHidden = false
likeSavedButton.tag = 1
}
else
{
self.likedbuttonFIlled.isHidden = true
likeSavedButton.tag = 0
self.numberOfLikesLabel.text = "\(String(-1))"
}
}
//MARK: FUNCTIONS
func generateCellsforDailymotivation(_MotivationdataMODEL : MotivatioNDataModel) {
DMtextLabel.text = _MotivationdataMODEL.motivationDailyScriptureModel
DMtitleLabel.text = _MotivationdataMODEL.motivationTitleModel
numberOfLikesLabel.text = "\(String(_MotivationdataMODEL.motivationDailyNumberOfLikes))"
}
}
import UIKit
import Firebase
//MARK: MAINVIEW MOTIVATION
class motivationviewcontroller : UIViewController,UITableViewDataSource ,UITableViewDelegate{
var motivationThoughts = [motivationDailyModel]()
var Mous = motivationDailyModel()
var tableview : UITableView!
override func viewDidLoad() {
print("madicc")
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()
self.tableview.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
//loaddailymotivation()
self.tableview.reloadData()
}
//======================================================================
//MARK: LOADS THE DATA INTO THE TABLEVIEW
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!
}
//gets the data from firebase and loads it into an array that will be called in generateCELLS
//MARK: FUNCTION THAT HANDLES GETTING THE DATA FROM FIREBASE
func loaddailymotivation() {
FirebaseReferece(.MotivationDAILY).addSnapshotListener { (snapshot, error) in
if (error != nil) {
print(error!.localizedDescription)
} else{
guard let snapshot = snapshot else {return}
for allDocuments in snapshot.documents {
let data = allDocuments.data()
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)
}
}
self.tableview.reloadData()
}
}