在帖子下显示评论

时间:2017-09-10 00:15:20

标签: ios swift uitableview

我对此很陌生,并且无法在包含两个单元格的表格视图中显示帖子的评论(一个单元格=帖子,第二个单元格=评论)。这是我的View Controller代码:

import UIKit

class PostDetailViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    var postId = ""
    var post = Post()
    var user = User()
    var comments = [Comment]()
    var users = [User]()

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        print("postId = \(postId)")
        loadPost()
        loadComments()
    }

    func loadPost() {
        API.Post.observePost(withId: postId) { (post) in
            guard let postUid = post.uid else {
                return
            }
            self.fetchUser(uid: postUid, completed: {
                self.post = post
                self.tableView.reloadData()
            })
            self.navigationItem.title = post.title
        }
    }

    func fetchUser(uid: String, completed: @escaping () -> Void ) {
        API.User.observeUser(withId: uid, completion: {
            user in
            self.user = user
            completed()
        })
    }

    func loadComments() {API.Post_Comment.REF_POST_COMMENTS.child(self.postId).observe(.childAdded, with: {
            snapshot in
            API.Comment.observeComments(withPostId: snapshot.key, completion: { comment in
                self.fetchUser(uid: comment.uid!, completed: {
                    self.comments.append(comment)
                    self.tableView.reloadData()
                })

            })
        })
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "Detail_CommentSegue" {
            let commentVC = segue.destination as! CommentViewController
            let postId = sender as! String
            commentVC.postId = postId
        }

        if segue.identifier == "Detail_ProfileUserSegue" {
            let profileVC = segue.destination as! ProfileUserViewController
            let userId = sender as! String
            profileVC.userId = userId
        }

    }

    }

    extension PostDetailViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return comments.count + 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "DetailPostCell", for: indexPath) as! DetailTableViewCell
            cell.post = post
            cell.user = user
            cell.delegate = self
            return cell
        } else {
            let commentCell = tableView.dequeueReusableCell(withIdentifier: "Detail_CommentCell") as! CommentTableViewCell
            let comment = comments[indexPath.row]
            let user = users[indexPath.row]
            commentCell.comment = comment
            commentCell.user = user
            return commentCell
        }
    }
    }

    extension PostDetailViewController: DetailTableViewCellDelegate {
    func goToCommentVC(postId: String) {
        performSegue(withIdentifier: "Detail_CommentSegue", sender: postId)
    }
    func goToProfileUserVC(userId: String) {
        performSegue(withIdentifier: "Detail_ProfileUserSegue", sender: userId)
    }
}

我得到的错误是:

let comment = comments[indexPath.row]
  

"致命错误:指数超出范围"

有评论,它们出现在评论视图控制器上没有问题。我意识到错误与调用两个单元格有关,但我无法找到解决方法。

1 个答案:

答案 0 :(得分:2)

从数组中获取值时,您没有考虑第一行。

简单的解决方法是更新cellForRowAt,如下所示:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "DetailPostCell", for: indexPath) as! DetailTableViewCell
        cell.post = post
        cell.user = user
        cell.delegate = self
        return cell
    } else {
        let commentCell = tableView.dequeueReusableCell(withIdentifier: "Detail_CommentCell") as! CommentTableViewCell
        let comment = comments[indexPath.row - 1] // here
        let user = users[indexPath.row - 1] // here
        commentCell.comment = comment
        commentCell.user = user
        return commentCell
    }
}

请注意标记为// here的两个小更改。我们的想法是comment[0]位于第1行。

一些更好的建议:

  1. 没有多个数组。为您的数据准备一个数组。定义一个包含一行所有数据的结构。然后有一个这样的结构数组。这使您的数据更易于处理,并使排序和过滤等操作变得更加简单。
  2. 考虑将不同的数据放在不同的部分而不是全部放在一个部分中。