Search code examples
iosuitableviewswiftparse-platformnsindexpath

Set dynamic Custom Cell from certain row


I'm making an social function in which people can comment on pictures. The only dynamic cell is also the comment cell. I'm using Parse for this.

How can I get different comments on each comment cell? I tried accessing indexPath.row, but it gives me a error: '*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]'

Now playing with a custom NSIndexPath but I only managed to acces the forRow method manually. Result is that the comments are all the same.

  • Row 0 & 1 are working.
  • Using Storyboard.
  • userComments is the Mutable Array in which the comments are being loaded.
  • The println(comments) gives me 2 objects which are the same.

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return userComments.count + 2
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if indexPath.row == 0 {
        let Postcell:PostTableViewCell = tableView.dequeueReusableCellWithIdentifier("imageCell") as PostTableViewCell
        ....
        return Postcell
    }
    if indexPath.row == 1 {
        let likeCell:likedTableViewCell = tableView.dequeueReusableCellWithIdentifier("likeCell") as likedTableViewCell
        ....
        return likeCell
    }else {
        let commentCell:commentTableViewCell = tableView.dequeueReusableCellWithIdentifier("commentCell") as commentTableViewCell
    
        let commentIndex:NSIndexPath = NSIndexPath(forRow: 0, inSection: 0)
        let comment:PFObject = userComments.objectAtIndex(commentIndex.row) as PFObject
    
        println(comment)
    
        // Comment Label
        commentCell.commentLabel.text = comment.objectForKey("content") as String!
        commentCell.userImageView.image = UIImage(named: "dummy")
    
        return commentCell
        }
    }
    

Solution

  • That is happening because in your last bit you are always asking for row 0 section 0 in parse, you will need something like this:

    else {
    let commentCell:commentTableViewCell = tableView.dequeueReusableCellWithIdentifier("commentCell") as commentTableViewCell
    
    //indexPath.row is the actual row of the table, 
    //so you will have for table row 2 parse row 0, for 3 row 1 and so on
    let commentIndex:NSIndexPath = NSIndexPath(forRow: indexPath.row-2, inSection: 0)
    let comment:PFObject = userComments.objectAtIndex(commentIndex.row) as PFObject
    
    println(comment)
    
    // Comment Label
    commentCell.commentLabel.text = comment.objectForKey("content") as String!
    commentCell.userImageView.image = UIImage(named: "dummy")
    
    return commentCell
    }