Search code examples
swifttimestampjsqmessagesviewcontroller

Changing JSQmessageVC Timestamp logic in swift


How can i change the timestamp logic to avoid repeating times as shown in the screenshot below?

Here is my code..

override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForCellTopLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! {

    if indexPath.item % 3 == 0 {

        let message = messages[indexPath.item]

        return JSQMessagesTimestampFormatter.sharedFormatter().attributedTimestampForDate(message.date)
    }
    return nil
}

override func collectionView(collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForCellTopLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat {

    if indexPath.item % 3 == 0 {
        return kJSQMessagesCollectionViewCellLabelHeightDefault
    }
    return 0.0
}

enter image description here


Solution

  • If we compare the previous messages date too the current messages date we can display only when the time changes. You can leave the every third message if you want or remove it

     if indexPath.item % 3 == 0 {          //optional
    
      let previousMessage = messages[indexPath.item - 1]
      let message = messages[indexPath.item]
        if message.date == previousMessage {
          return JSQMessagesTimestampFormatter.sharedFormatter().attributedTimestampForDate(message.date)
        else { 
          return nil
        }
      }
    return nil
    

    You may need to make sure that it is not the first message because messages[indexPath.item - 1] will be out of range. But besides that it should solve your question. Good luck 🖖🏽