2

I am trying to make a chat app and I am using JSQMessagesViewController library. My Chat View show all the messages with their date and time but I am facing some little bit of problem with this library. My problem is I wanna show message date only Once. Suppose: Yesterday date contains 10 messages and today date contains 15 messages

and I wanna show Only single date of these messages as not repeat dates for every messages enter image description here

Umesh Verma
  • 876
  • 7
  • 28

2 Answers2

4

Well you need to determine if the message is the first of that day. Then return nil for all the others till a new day.

I created a function to determine if my message was the first sent by that individual. It looks like this

func firstMessageOfTheDay(indexOfMessage: NSIndexPath) -> Bool { 
  let messageDate = messages[indexOfMessage.item].date
  guard let previouseMessageDate = messages[indexOfMessage.item - 1].date else {
    return true // because there is no previous message so we need to show the date
  }
    let day = Calendar.current.component(.day, from: messageDate)
    let previouseDay = Calendar.current.component(.day, from: previouseMessageDate)
    if day == previouseDay {
        return false
    } else {
        return true
    }
}

Then call that in the appropriate function. Hope that helps let me know if you have any other questions.

Hashem Aboonajmi
  • 13,077
  • 8
  • 66
  • 75
Dan Leonard
  • 3,325
  • 1
  • 20
  • 32
1

Use this method to do this.

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

You have to check the message date if the date is different then previous message date return date in which format you want otherwise return nil.

Surjeet Rajput
  • 1,251
  • 17
  • 24