我尝试添加评论后,UITableView无法重新加载

时间:2018-10-28 04:19:42

标签: reloaddata

我很难将我的新帖子添加到表格中(动态或重新加载整个表格)。我尝试使用两种方式。 这是我的代码。

@IBAction函数postCommentAction(_发件人:任何){

    ProgressHUD.show("", interaction: true)
    let commentTimestamp = ServerValue.timestamp()
    let postRef = DBProvider.instance.newsFeedRef.child(postId)
    let commentsRef =  postRef.child("usercomments").child(postRef.childByAutoId().key)
    commentsRef.setValue(["userId": AVAuthService.getCurrentUserId(),"type": "", "comments": writeComment.text as String, "commentTimestamp": commentTimestamp], withCompletionBlock:{(error, ref) in
        if error != nil{
            ProgressHUD.showError(error!.localizedDescription)
            return
        }
        let commentHeight = CommonUtils.heightForView(text: self.writeComment.text, font: UIFont(name: "Verdana", size: 13)!,width: self.tableView.frame.width-60)
        let height = commentHeight < 40 ? 40 : commentHeight
        self.tableView.contentSize = CGSize(width: self.view.frame.size.width, height:self.tableView.contentSize.height + height + 40)
        self.scrollView.contentSize = CGSize(width: self.view.frame.size.width, height:self.scrollView.contentSize.height + height + 40)
        let comment = PostComment(profileImageUrl: "", userId: AVAuthService.getCurrentUserId(), type: "", comments: self.writeComment.text, commentDate: self.commentDateDouble)
        self.writeComment.text = ""
        self.textViewDidChange(self.writeComment)
        self.textViewDidEndEditing(self.writeComment)
        self.getCommentsCount()
        self.insertPostedCommentInTable(comment:comment)
        ProgressHUD.dismiss()
    })

}

func insertPostedCommentInTable(comment:PostComment){
    DBProvider.instance.userRef.child(comment.userId).observeSingleEvent(of: DataEventType.value){
        (snapShot:DataSnapshot) in
        comment.profileImageUrl = ((snapShot.value as! NSDictionary)["ProfileImageURL"] as? String)!
        print("profileImageUrl in fetchProfileImageURL: \(comment.profileImageUrl)")
        self.comments.append(comment)
        let indexPath = IndexPath (row: self.comments.count - 1,section:0)
        print("indexpath: \(indexPath)")
        self.tableView.beginUpdates()
        self.tableView.insertRows(at: [indexPath], with: .automatic)
        self.tableView.endUpdates()
        //self.tableView.reloadData()
        print("self.comments: \(self.comments)")

    }
}

func getCommentsCount(){
    DBProvider.instance.newsFeedRef.child(postId).child("usercomments").queryOrdered(byChild: "type").queryEqual(toValue: "").observeSingleEvent(of: DataEventType.value){
        (snapShot:DataSnapshot) in
        self.writeCommentLabel.text = String(snapShot.childrenCount) + " Comments"
    }
}

扩展NewsNewedViewController:UITableViewDataSource,UITableViewDelegate {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return comments.count
}

func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 10
}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    print("in cellforrowatindexpath")
    let cell = tableView.dequeueReusableCell(withIdentifier: "CommentsTableCell") as! CommentsTableCell

    let url = comments[indexPath.row].profileImageUrl as String
    cell.profileImageView.loadImageUsingCache(urlStr: url)
    cell.comment.text = comments[indexPath.row].comments as String
    let commentAtRow = comments[indexPath.row].comments as String

    let hgt = CommonUtils.heightForView(text: commentAtRow, font:UIFont(name: "Verdana", size: 13)! ,width: UIScreen.main.bounds.width - 60)
    let height = hgt < 40 ? 40: ceil(hgt)
    let heightConstraint = NSLayoutConstraint(item: cell.commentedDate, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: cell, attribute: NSLayoutAttribute.top, multiplier: 1, constant: (height+10))

    cell.addConstraint(heightConstraint)

    let commentedTimestamp = (comments[indexPath.row].commentDate)/1000

    let currentTimestamp = NSDate().timeIntervalSince1970


    let duration = currentTimestamp - commentedTimestamp
    var commentString = ""
    let minutes = Int(duration/60)
    let hours = Int(duration/3600)
    let days = Int(duration/86400)
    let months = Int(duration/2592000)
    let years = Int(duration/31104000)
    if duration < 60 {
        commentString = "few seconds ago"
    }
    else if duration < 300 {
        commentString = "few minutes ago"
    }
    else if duration < 3600 {
        if minutes < 2{
            commentString = "\(minutes) minute ago"
        }else if minutes >= 2 {
            commentString = "\(minutes) minutes ago"
        }
    }
    else if duration < 86400 {
        if hours < 2 {
            commentString = "\(hours) hour ago"
        }else if hours >= 2 {
            commentString = "\(hours) hours ago"
        }
    }
    else if duration < 2592000 {
        if days < 2 {
            commentString = "\(days) day ago"
        }else if days >= 2 {
            commentString = "\(days) days ago"
        }
    }
    else if duration < 31104000 {
        if months < 2 {
            commentString = "\(months) month ago"
        }else if months >= 2 {
            commentString = "\(months) months ago"
        }
    }
    else if duration > 31104000 {
        if years < 2 {
            commentString = "\(years) year ago"
        }else if years >= 2 {
            commentString = "\(years) years ago"
        }
    }
    else{
        commentString = "long time back"
    }

    cell.commentedDate.text = "\(commentString)"

    cell.commentedDate.font = UIFont(name: "Verdana", size: 12)
    cell.commentedDate.textColor = UIColor.gray

    return cell
}

func tableView(_ tableView:UITableView,heightForRowAt indexPath:IndexPath)-> CGFloat {

let estimatedHgt = CommonUtils.heightForView(text: comments[indexPath.row].comments, font: UIFont(name: "Verdana", size: 13)!,width: UIScreen.main.bounds.width - 60 )
    let height = estimatedHgt < 40 ? 40 : ceil(estimatedHgt)
    return height + 40
}

}

0 个答案:

没有答案