Search code examples
jsqmessagesviewcontroller

is it possible to hide message bubble


chat with system messages

I'm using JSQMessagesViewController to implement chat in my iOS app. I need to display some system messages in the middle of the screen (see attached picture). I was hoping that I can achieve that by using the message bottom label and not showing the message bubble. But I haven't found a way to hide the message bubble. Is it possible? Thanks.


Solution

  • I sort of achieved what I need by overriding collectionView sizeForItemAtIndexPath function and return a height of kJSQMessagesCollectionViewCellLabelHeightDefault, then return nil for both messageBubbleImageDataForItemAtIndexPath and avatarImageDataForItemAtIndexPath

    override func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        let userMessageCellSize = super.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAtIndexPath: indexPath)
        let message = messages[indexPath.item]
        if message.type == MessageType.System {
            // for system message, only show bottom label, plus the top label when timestamp needs to be displayed
            // this will hide the avatar image and message bubble which are not needed for system messages.
            var newHeight: CGFloat = 0
            if (shouldDisplayTimestamp(indexPath)) {
                newHeight = kJSQMessagesCollectionViewCellLabelHeightDefault * 2
            } else {
                newHeight = kJSQMessagesCollectionViewCellLabelHeightDefault
            }
            return CGSizeMake(userMessageCellSize.width, newHeight)
        } else {
            return super.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAtIndexPath: indexPath)
        }
    }
    
    override func collectionView(collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageBubbleImageDataSource! {
        let message = messages[indexPath.item]
    
        if message.type == MessageType.System {
            return nil
        }
    
        if message.senderId == senderId{
            return self.outgoingBubbleImageView
        } else {
            return self.incomingBubbleImageView
        }
    }
    
    override func collectionView(collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageAvatarImageDataSource! {
        let message = messages[indexPath.item]
    
        if message.type == MessageType.System {
            return nil
        }
    
        if let avatar = avatars[message.senderDisplayName] {
            return avatar
        } else {
            setupAvatarImage(message.senderDisplayName, imageUrl: message.profileImgUrl, incoming: true)
            return avatars[message.senderDisplayName]
        }
    }