简体   繁体   English

如何通过单击表格视图单元格上的按钮来获取文档ID?

[英]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. 我在视图控制器中使用除主故事板之外的xib文件来显示帖子项目,并且有评论按钮,单击该按钮应转到另一个页面,其中有与该帖子相关的评论列表。 for that I need to pass the documentId of the post as well so that the accurate segue operation could be performed. 为此,我还需要传递帖子的documentId,以便可以执行准确的segue操作。

I have tried my things by searching google but till now nothing had worked for me. 我已经通过搜索google尝试了自己的事情,但是到目前为止,对我来说没有任何作用。

if any more details are required please let me know 如果需要更多详细信息,请告诉我

HomeViewController Swift Class HomeViewController Swift类

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 PostViewCell类

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 在PostTableViewCell中创建注释按钮的出口

class PostTableViewCell: UITableViewCell {

@IBOutlet weak var btnComment: UIButton!

now in cellForRowAtIndex do add following line too 现在在cellForRowAtIndex中也添加以下行

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)

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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