简体   繁体   中英

How do I get the document id by clicking the button on the tableview cell?

I am using a xib file apart from the main storyboard in my view controller for displaying a post item, and there is comment button, upon being clicked it should go to another page where the list of comments related to that post is available. for that I need to pass the documentId of the post as well so that the accurate segue operation could be performed.

I have tried my things by searching google but till now nothing had worked for me.

if any more details are required please let me know

HomeViewController Swift Class

class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var tableView:UITableView!

    var posts = [Post]()
    var db: Firestore!

    var postKey:String = ""
    private var documents: [DocumentSnapshot] = []
    //public var posts: [Post] = []
    private var listener : ListenerRegistration!


    var detailView: Post?


    override func viewDidLoad() {
        super.viewDidLoad()

        db = Firestore.firestore()

        self.navigationController?.navigationBar.isTranslucent = false
        tableView = UITableView(frame: view.bounds, style: .plain)

        let cellNib = UINib(nibName: "PostTableViewCell", bundle: nil)
        tableView.register(cellNib, forCellReuseIdentifier: "postCell")
        tableView.backgroundColor = UIColor(white: 0.90,alpha:1.0)
        view.addSubview(tableView)

        var layoutGuide:UILayoutGuide!

        if #available(iOS 11.0, *) {
            layoutGuide = view.safeAreaLayoutGuide
        } else {
            // Fallback on earlier versions
            layoutGuide = view.layoutMarginsGuide
        }

        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.delegate = self
        tableView.dataSource = self
        tableView.reloadData()
        retrieveAllPosts()
        //checkForUpdates()
        postKey = detailView!._documentId


    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tableView.reloadData()
    }

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

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
        cell.set(post: posts[indexPath.row])
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let post = self.posts[indexPath.row]

        performSegue(withIdentifier: "toCommentsList", sender: indexPath)
    }

   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
       //segue.forward(posts, to: segue.destination)
        guard let details = segue.destination as? CommentListViewController,
        let index = tableView.indexPathForSelectedRow?.row

       else {
        return
        }
       // details.detailView = posts[index]



    }
    //I tried to connect this action to the button in the XIB file but not able to do so.
    @IBAction func toCommentsSection(_ sender: Any) {

        print(postKey + "hello")
        //  let postId11 = detailView?._documentId
        performSegue(withIdentifier: "toCommentsList", sender: self)

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        var vc = segue.destination as! CommentListViewController
        vc.postId = postKey
    }

}

PostViewCell Class

class PostTableViewCell: UITableViewCell {

    @IBOutlet weak var usernameLabel: UILabel!
   @IBOutlet weak var profileImageView: UIImageView!
    @IBOutlet weak var subtitleLabel: UILabel!
    @IBOutlet weak var postTextLabel: UILabel!



    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code

       // profileImageView.layer.cornerRadius = profileImageView.bounds.height / 2
       // profileImageView.clipsToBounds = true
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    func set(post:Post) {
      if let userprofileImagUrl =  post._postuserprofileImagUrl,
            let imageUrl = URL(string: userprofileImagUrl) {
            ImageService.getImage(withURL: imageUrl) { image in
                self.profileImageView.image = image
            }
        }
        usernameLabel.text = post._username
        postTextLabel.text = post._postContent
        subtitleLabel.text = post._postcategory
    }

}

In PostTableViewCell create outlet of comment buttons

class PostTableViewCell: UITableViewCell {

@IBOutlet weak var btnComment: UIButton!

now in cellForRowAtIndex do add following line too

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
cell.btnComment.tag = indexPath.row
cell.btnComment.addTarget(self, action: #selector(self. toCommentsSection(sender:)) , for: .touchUpInside)
    cell.set(post: posts[indexPath.row])
    return cell
}

and in

 @IBAction func toCommentsSection(_ sender: Any) {

    let commentbutton = sender as! UIButton
    let post = posts[commentbutton.tag]
    postKey = post.postKey // or what key value it is 
    print(postKey + "hello")
    //  let postId11 = detailView?._documentId
    performSegue(withIdentifier: "toCommentsList", sender: self)

}

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