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

时间:2019-09-16 11:22:19

标签: ios swift firebase google-cloud-firestore uibutton

我正在使用除视图控制器中主要故事板之外的xib文件来显示帖子项目,并且有评论按钮,单击该按钮应转到另一个页面,该页面提供了与该帖子相关的评论列表。为此,我还需要传递帖子的documentId,以便可以执行准确的segue操作。

我通过搜索google尝试了自己的事情,但到目前为止,对我来说没有任何帮助。

如果需要更多详细信息,请告诉我

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 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
    }

}

1 个答案:

答案 0 :(得分:0)

在PostTableViewCell中创建注释按钮的出口

class PostTableViewCell: UITableViewCell {

@IBOutlet weak var btnComment: UIButton!

现在在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
}

 @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)

}