CoderCody CoderCody - 7 months ago 19
Swift Question

What's someones preferred method for adding a comments section to a TableViewCell?

I am currently using a tableview to display a individual "Posts." In each tableview cell is a unique Post. I would like to add a collection of "comments" into each cell. The only way I can think about collecting comments is to add another TableView inside the Post's cell. What is some preferred methods to accomplishing this? It seems pretty complicated to use a TableView inside another TableViews Cell.


I don't think it's a good idea.

Create N sections in your table view, one section for every post.

For every section

  • the cell at row 0 will be populated with the post data
  • every cell in the following rows will be populated with the comments data.


struct PostModel {
    let title: String
    let comments: [String]

class Posts: UITableViewController {
    private var posts: [PostModel] = ... // TODO

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return posts.count

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return posts[section].comments.count + 1

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let post = posts[indexPath.section]

        let cell = tableView.dequeueReusableCellWithIdentifier("StandardCell") ?? UITableViewCell(style: .Default, reuseIdentifier: "StandardCell")

        if indexPath.row == 0 {
            cell.textLabel?.text = post.title
            return cell
        } else {
            let comment = post.comments[indexPath.row-1]
            cell.textLabel?.text = comment
            return cell