Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make the sender display name appear with JSQMessageViewController?

I have the following function that gets called for adding a message:

    func addMessage(text: String, displayName: String) {
        let message = JSQMessage(senderId: "tester", displayName: displayName, text: text)
        messages.append(message)

        finishReceivingMessage()

}

Then in this function

    override func collectionView(collectionView: JSQMessagesCollectionView!,
    messageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageData! {
        return messages[indexPath.item]
}

I return the message date for that indexPath. The message appears correctly but there is no display name.

like image 732
Tob Avatar asked Mar 14 '16 23:03

Tob


2 Answers

I think you are missing the attributedTextForMessageBubbleTopLabelAtIndexPath should look something like this

 override func collectionView(collectionView: JSQMessagesCollectionView?, attributedTextForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! {
    let message = messages[indexPath.item]
    switch message.senderId {
    case CURRENTUSERID:
        return nil
    default:
        guard let senderDisplayName = message.senderDisplayName else {
            assertionFailure()
            return nil
        }
        return NSAttributedString(string: senderDisplayName)

    }
}

Edit:

Also make sure you give the label a hight with this function

override func collectionView(collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
   return 13 //or what ever height you want to give
}    

Good Luck 🚀

like image 102
Dan Leonard Avatar answered Nov 16 '22 03:11

Dan Leonard


New Updated Methods

override func collectionView(_ collectionView: JSQMessagesCollectionView!, attributedTextForMessageBubbleTopLabelAt indexPath: IndexPath!) -> NSAttributedString!
     {
        let message = messages[indexPath.item]

        if message.senderId == senderId {
            return nil
        } else {
            guard let senderDisplayName = message.senderDisplayName else {
                assertionFailure()
                return nil
            }
            return NSAttributedString(string: senderDisplayName)

        }

    }

     override func collectionView(_ collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForMessageBubbleTopLabelAt indexPath: IndexPath!) -> CGFloat
    {
        //return 17.0
        let message = messages[indexPath.item]

        if message.senderId == senderId {
            return 0.0
        } else {

            return 17.0

        }
    }
like image 44
Satish Babariya Avatar answered Nov 16 '22 02:11

Satish Babariya