Search code examples
swiftfirebasefirebase-realtime-databasejsqmessagesviewcontroller

Swift - JSQMessagesViewController Showing incoming avatar email or username


I'm developing a chat app,And I have thisenter image description here

The problem now is how can i show the username on top of the message bubbles like this on the demo? https://raw.githubusercontent.com/jessesquires/JSQMessagesViewController/develop/Screenshots/screenshot2.png

I'm looking for override func collectionView(collectionView: JSQMessagesCollectionView!, senderDisplayNameDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageAvatarImageDataSource! But I think it's not possible. What do you think the solution here? Thanks!


Solution

  • For viewing userName top of the incoming message JSQ is having below methods.

    //MARK: To View  usernames above bubbles
    
    override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! {
        let message = messages[indexPath.item];
    
        // Sent by me, skip
        if message.sender() == sender {
            return nil;
        }
    
        // Same as previous sender, skip
        if indexPath.item > 0 {
            let previousMessage = messages[indexPath.item - 1];
            if previousMessage.sender() == message.sender() {
                return nil;
            }
        }
    
        return NSAttributedString(string:message.sender())
    }
    
    override func collectionView(collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
        let message = messages[indexPath.item]
    
        // Sent by me, skip
        if message.sender() == sender {
            return CGFloat(0.0);
        }
    
        // Same as previous sender, skip
        if indexPath.item > 0 {
            let previousMessage = messages[indexPath.item - 1];
            if previousMessage.sender() == message.sender() {
                return CGFloat(0.0);
            }
        }
    
        return kJSQMessagesCollectionViewCellLabelHeightDefault
    }
    

    The above code is worked for me, I hope it will work for you also. For more info you can see Demo

    https://github.com/jessesquires/JSQMessagesViewController