Search code examples
uitableviewswift3xibnsindexpath

Update particular row in tableviewcell in tableview in swift 3?


I am using tableviewcell.xib in table view. In that I have comment button, if I click on that I will navigate to another page so that I can comment, when I dismiss after commenting. It will come to tableview page, in that I want to update the comment count value without updating with service call . where I should add this code for updating cell.Please help me.

     let indexPath = IndexPath(item: sender.tag, section: 0)  
self.tableView.reloadRows(at: [indexPath], with: .automatic)

I am navigating like this

    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
    let commentPage = storyBoard.instantiateViewController(withIdentifier: "postCommentsPage") as! PostCommentViewController
    self.present(commentPage, animated: false, completion:nil)

Solution

  • What you need to do is to make one protocol like UpdateCommentCount and implement that protocol with your Controller where you are having this tableView after that in your PostCommentViewController make one instance property of type UpdateCommentCount, also in your tableController declare one property of type Int to hold the reference of tapped row.

    protocol UpdateCommentCount {
        func updateComment(with count:Int)
    }
    

    Now implement this UpdateCommentCount with yourController and add one Int property to hold the reference of tapped row and set it inside your button action where you are presenting your PostCommentViewController

    class YourController: UIViewController, UpdateCommentCount, UITableViewDelegate, UITableViewDataSource {
    
        var currentCommentRow = 0
    
        //Your other methods
    
        func commentButtonAction(_ sender: UIButton) {
            currentCommentRow = sender.tag
            let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
            let commentPage = storyBoard.instantiateViewController(withIdentifier: "postCommentsPage") as! PostCommentViewController
            commentPage.commentDelegate = self
            self.present(commentPage, animated: false, completion:nil)
        }
    
        func updateComment(with count:Int) {
            let dic = yourArray[self.currentCommentRow]
            dic["commentCount"] = count
            yourArray[self.currentCommentRow] = dic
            let indexPath = IndexPath(item: self.currentCommentRow, section: 0)  
            self.tableView.reloadRows(at: [indexPath], with: .automatic)
        }
    

    Now in PostCommentViewController declare one instance property named commentDelegate of type UpdateCommentCount and after simply call its delegate method when you successfully post comment.

    var commentDelegate: UpdateCommentCount
    

    Call updateComment after successfully posting new comment.

    commentDelegate.updateComment(with: newCount)