如何通过单击 tableview 单元格上的按钮获取文档 ID?

Posted

技术标签:

【中文标题】如何通过单击 tableview 单元格上的按钮获取文档 ID?【英文标题】:How do I get the document id by clicking the button on the tableview cell? 【发布时间】:2019-09-16 11:22:19 【问题描述】:

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

我已经通过搜索谷歌尝试了我的东西,但直到现在对我来说没有任何效果。

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

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
    


【问题讨论】:

发布到目前为止您尝试过的代码是什么? 好的,让我更新问题 @AbuUlHassan 代码已添加 所以你在故事板上有 CommentListViewController 或者它也是一个 xib ? 故事板上的 CommentListViewController 不在 xib 上 【参考方案1】:

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


【讨论】:

button IBACTION 将如何与按钮连接,因为它在 HomeViewController 文件中,我也尝试在 PostTableViewCell 中,但它无法识别“performSegue” addTarget 实际上是以编程方式连接 btnComment 和 toCommentsSection 但在 HomeViewController 中出现“使用未解析的标识符 'btnComment';”的错误 使用单元格。在 cellForRowAtIndexPath 中的 homeViewCONtroller 中的 btnComment 我也更新了答案道歉这是我的错误,同时尽快为您提供解决方案。

以上是关于如何通过单击 tableview 单元格上的按钮获取文档 ID?的主要内容,如果未能解决你的问题,请参考以下文章

如何使表格视图单元格上的按钮调用正确的 tableView:cellForRowAtIndexPath?

我的tableview单元格上的组件不可见

如何在 ipad 中的 tableview 单元格上显示弹出框单击

当点击单元格上的按钮时,将信息写入单元格中

如何在ios中的tableview单元格上的文本字段上返回文本字段上的键盘

我想在 tableview 单元格中显示文本字段数据,以替换 iphone 中单元格上的现有数据?