簡體   English   中英

如何通過單擊表格視圖單元格上的按鈕來獲取文檔ID?

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

我在視圖控制器中使用除主故事板之外的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
    }

}

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM