【问题标题】:How do I get the document id by clicking the button on the tableview cell?如何通过单击 tableview 单元格上的按钮获取文档 ID?
【发布时间】: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 上

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


【解决方案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
  • 我也更新了答案道歉这是我的错误,同时尽快为您提供解决方案。
猜你喜欢
  • 1970-01-01
  • 2019-04-25
  • 1970-01-01
  • 1970-01-01
  • 2020-10-20
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
  • 2017-11-19
相关资源
最近更新 更多