1

I am using JSQ Messages Controller to add a chat feature to my app, but I also managed to create one on my own with a collectionview. However Injust can‘t figure out how to show the profile picture just next to the last message of an user. For example he writes 3 messages and no one else in the chat does write anything in between. Now I just want to show only next to the third message the profile picture. When I return the items (cells) I just can edit the item I am about to return (at indexPath.item) though. I can make sure that the message before (at indexPath.item - 1) has the same senderID. But I can‘t check if the cell at indexPath.item + 1) is from the same sender. Since I am not able to check the second one, I have no clue how to solve my problem. I hope you understood what I want to do.

AlexVilla147
  • 283
  • 2
  • 15

1 Answers1

4

First I would like to point you to the new project that is taking over JSQMessageViewController since JSQMessageViewController is deprecated, It is called MessageKit.

Make a function to determine if it is the last message in a set.

//Check if it is the last message in all your messages
//Check that the next message is not sent by the same person. 
 func isLastInSet(indexOfMessage: IndexPath) -> Bool {
     if indexOfMessage.item == messages.count -1 {
       return true
     } else if {
        return messages[indexOfMessage.item].senderID() != messages[indexOfMessage.item + 1].senderID()
     }
 }

Now just add a call to isLastInSet within the avatarImageDataForItemAt if it returns a false set the image to nil

func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {   
    if let message = messages[indexPath.item]{
      if isLastInSet(indexOfMessage: indexPath) {
         return ImageData
      }
    }
  return nil
  } 
Dan Leonard
  • 3,325
  • 1
  • 20
  • 32
  • Thanks man, I just had to change little things to make it work!. I think swift 4 forced me to change it, but your idea was correct! – AlexVilla147 Oct 16 '17 at 17:47