简体   繁体   中英

How to access values in UIViewController class from TableCell class in Swift?

So, I have a UIViewController(PledgeViewController) with a TableView . When the user clicks on a UIButton(plusBtn) in the UITableViewCell(PledgeTableViewCell) of the TableView , I want to perform a write to my firebase database. But to get the exact path, I need a String(getID) from the PledgeViewController class which is received with a segue from the previous ViewController. With the MVC format that I'm using, how do I access values in the PledgeViewController to write to the database from the PledgeTableViewCell ?

在此处输入图片说明 My PledgeViewController.swift:

import UIKit
import Foundation
import FirebaseDatabase
import Firebase

class PledgeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{


    var getID: String!

    @IBOutlet weak var pledgeAmtLabel: UILabel!
    @IBOutlet weak var RewardChooseTable: UITableView!
    @IBAction func pledgeBtn(_ sender: Any) {
        //get the text from the label and run all the checks to see if the tickets are available

    }

    let RewardRef = Database.database().reference().child("Rewards")

    var rewards = [Rewards]()

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

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

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "TakePledgeCell", for: indexPath) as! PledgeTableViewCell
        let reward = rewards[indexPath.row]
        cell.reward = reward
        return cell

    }



    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        RewardRef.child(getID).observe(.value, with: { (snapshot) in
            self.rewards.removeAll()

            for child in snapshot.children {
                let childSnapshot = child as! DataSnapshot
                let reward = Rewards(snapshot: childSnapshot)
                self.rewards.insert(reward, at: 0)
            }

            self.RewardChooseTable.reloadData()
        })

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        print("The id received from the SingleViewControl is:" + getID)
}

}

My PledgeTableViewCell.swift:

import UIKit
import Firebase
import FirebaseDatabase

class PledgeTableViewCell: UITableViewCell {


    @IBOutlet weak var rewardAmtLabel: UILabel!
    @IBOutlet weak var ticketClasslabel: UILabel!
    @IBOutlet weak var ticketDescLabel: UILabel!

    @IBOutlet weak var ticketCountLabel: UILabel!
    @IBOutlet weak var plusBtn: UIButton!
    @IBOutlet weak var minusBtn: UIButton!
    var ref: DatabaseReference!
    var artcallid: Int!

    @IBAction func minusBtn(_ sender: Any) {
    }


    var reward: Rewards! {
        didSet {

            rewardAmtLabel.text = "Rs. " + String(reward.rewardAmt)
            ticketClasslabel.text = reward.reward_class_name
            ticketDescLabel.text = reward.reward_desc
            print(reward.reward_class_name + " is one of the rewards")

        }

    }

    @IBAction func plusBtn(_ sender: AnyObject) {


    }


}

Rewards.swift:

import Foundation
import Firebase
import FirebaseDatabase

class Rewards {
    let ref: DatabaseReference!
  //  let countRef: DatabaseReference!
    var rewardAmt: Int!
    var rewardsLeft: Int!
    var reward_class_name: String = ""
    var reward_amt: String = ""
    var reward_desc: String = ""
    var rewardID: String = ""
    var tickUpCount = 0
    var tickDownCount = 0

    init(text: String) {
        ref = Database.database().reference().child("Fund").childByAutoId()
      //  countRef = Database.database().reference().child("Testing").childByAutoId()
    }



   init(snapshot: DataSnapshot)
    {
        ref = snapshot.ref
        if let value = snapshot.value as? [String : Any] {
            rewardAmt = value["reward_ticket_amount"] as! Int
            reward_class_name = value["reward_ticket_amount_class_name"] as! String
            reward_amt = value["reward_ticket_amount_txt"] as! String
            reward_desc = value["reward_ticket_class_desc"] as! String
            rewardsLeft = value["rewards_left"] as! Int
            rewardID = snapshot.key

        }
    }

    }

extension Rewards{

    func countUp(){
        tickUpCount += 1
        ref.child("uppingTicket").setValue(tickUpCount)

    }

}

You can try to add a new var

class PledgeTableViewCell: UITableViewCell {

    var currentID = ""
}

and set it in cellForRowAt

cell.currentID = getID

You can try with closure

class PledgeTableViewCell: UITableViewCell {
  //Define a closure

    var closure:(() -> Void)? = nil

@IBAction func plusBtn(_ sender: AnyObject) {

 // Do you stuff

   closure?()
    }
}

    class PledgeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{

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

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

            let reward = rewards[indexPath.row]
            cell.reward = reward
            cell.closure = {
        // You will get the callback in this block
       // You can define the parameterized closure to return the value

    }
            return cell
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM