> ## Documentation Index
> Fetch the complete documentation index at: https://www.cometchat.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Message Bubbles

> Customise how each message type is drawn in the CometChat iOS UI Kit v6: a BubbleFactory in SwiftUI, a CometChatMessageTemplate in UIKit, keyed by category and type.

The message list draws every message with a bubble chosen by the message's **category** and
**type**. You can replace how one kind is drawn — a built-in such as text or image, or a custom
message type of your own — and keep the Kit's rendering for everything else.

The two toolkits use different names for this:

* **SwiftUI** (`CometChatSwiftUI`) uses a **`BubbleFactory`**. You write a
  struct that names a `MessageKind` and returns SwiftUI views.
* **UIKit** (`CometChatUIKit`) uses a **`CometChatMessageTemplate`**. You
  build a template with a category, a type and closures that return `UIView`s.

> [accordion] AI Integration Quick Reference
>
> ```json theme={null}
> {
>   "concept": "Per-message-type bubble customisation",
>   "swiftui": {
>     "package": "CometChatSwiftUI",
>     "type": "BubbleFactory (protocol, Sendable)",
>     "key": "var kind: MessageKind — MessageKind(category:type:) or .text, .image, .video, .audio, .voiceNote, .file, .sticker, .poll, .meeting, .document, .whiteboard, .card, .aiAssistant, .groupAction, .audioCall, .videoCall",
>     "required": "content(_ message: ChatMessage, _ alignment: MessageAlignment) -> AnyView",
>     "optionalSlots": ["leadingView", "headerView", "replyView", "statusInfoView", "bottomView", "footerView", "threadView", "bubbleView", "style(for:) -> MessageBubbleStyle?"],
>     "register": "CometChatMessageList(bubbleFactories: [any BubbleFactory]) — also CometChatThreadHeader, CometChatPinnedMessages, CometChatMessageInformation, CometChatMessageBubble(factory:)",
>     "builtIns": ["TextBubbleFactory", "ImageBubbleFactory", "VideoBubbleFactory", "FileBubbleFactory", "AudioBubbleFactory", "VoiceNoteBubbleFactory", "StickerBubbleFactory", "PollBubbleFactory", "MeetingBubbleFactory", "CollaborativeBubbleFactory(kind:)", "CardBubbleFactory", "AIAssistantBubbleFactory", "GroupActionBubbleFactory", "CallActionBubbleFactory(kind:)"]
>   },
>   "uikit": {
>     "package": "CometChatUIKit",
>     "type": "CometChatMessageTemplate (NSObject, @objc)",
>     "key": "category: String, type: String (kind: MessageKind is derived)",
>     "slotSignature": "(BaseMessage?, MessageBubbleAlignment, UIViewController?) -> UIView?",
>     "slots": ["contentView", "bubbleView", "headerView", "footerView", "bottomView", "statusInfoView", "replyView", "leadingView (property only)", "threadView (property only)"],
>     "options": "(BaseMessage?, Group?, UIViewController?) -> [CometChatMessageOption]?",
>     "register": "CometChatMessageList.set(templates:) replaces, add(templates:) adds — also CometChatThreadHeader.set(templates:), CometChatMessageInformation.set(templates:)"
>   },
>   "rules": [
>     "One factory/template per kind; the last registered wins.",
>     "A deleted message always draws the built-in tombstone.",
>     "A custom type must be added to messagesRequestBuilder's types, or it is never fetched.",
>     "A kind nothing draws shows 'Unsupported: category_type'."
>   ]
> }
> ```

## When to Use This

* Draw a **custom message type** — a contact card, an order receipt, a location.
* Replace how a **built-in** type is drawn — text, image, file …
* Replace the **whole row** rather than only the bubble's content.
* Change one region of a bubble — the avatar, the sender name, the status line, the reactions —
  for one kind only.

To change a region for **every** kind, use the message list's own view slots instead — see
[Message List](https://www.cometchat.com/docs/ui-kit/ios/v6/message-list.md). To change colours and fonts without
replacing views, see [Message Bubble Styling](https://www.cometchat.com/docs/ui-kit/ios/v6/message-bubble-styling.md).

## Prerequisites

* The `CometChatSwiftUI` or `CometChatUIKit` product added from
  `https://github.com/cometchat/cometchat-uikit-ios.git` (from `6.0.0-beta.1`, iOS 18).
* The Kit initialised and a user logged in.
* A `CometChatMessageList` on screen.

## Quick Start

This example draws a custom message of type `contact` as a card with a name and a phone number.

> [tab] SwiftUI
>
> Write a factory: name the kind, and return the content.
>
> ```swift ContactBubbleFactory.swift theme={null}
> struct ContactBubbleFactory: BubbleFactory {
>     var kind: MessageKind { MessageKind(category: "custom", type: "contact") }
>
>     @MainActor func content(_ message: ChatMessage, _ alignment: MessageAlignment) -> AnyView {
>         AnyView(ContactCard(message: message))
>     }
> }
>
> struct ContactCard: View {
>     let message: ChatMessage
>     // The resolved style of the bubble being drawn — incoming and outgoing differ.
>     @Environment(\.cometChatMessageBubbleStyle) private var bubble
>
>     var body: some View {
>         VStack(alignment: .leading, spacing: 2) {
>             Text(value("name") ?? "Contact").font(.headline)
>             if let phone = value("phone") { Text(phone).font(.subheadline) }
>         }
>         .foregroundStyle(bubble?.textColor ?? .primary)
>         .padding(12)
>     }
>
>     private func value(_ key: String) -> String? {
>         if case .string(let text)? = message.custom?.data[key] { return text }
>         return nil
>     }
> }
> ```
>
> Register it on the list, and ask the list to fetch your type:
>
> ```swift ChatScreen.swift theme={null}
> struct ContactChatScreen: View {
>     let user: CometChatSDK.User
>
>     var body: some View {
>         CometChatMessageList(
>             user: user,
>             messagesRequestBuilder: {
>                 MessagesRequest.MessageRequestBuilder()
>                     .set(types: MessageListStore.defaultMessagesTypes + ["contact"])
>                     .set(categories: MessageListStore.defaultMessagesCategories)
>                     .set(limit: 30)
>                     .hideReplies(hide: true)
>             },
>             bubbleFactories: [ContactBubbleFactory()]
>         )
>     }
> }
> ```

> [tab] UIKit
>
> Build a template with the category, the type and a `contentView` closure, register it on the
> list, and ask the list to fetch your type — **before** `set(user:)`:
>
> ```swift ChatViewController.swift theme={null}
> let contact = CometChatMessageTemplate(category: "custom", type: "contact", contentView: { message, _, _ in
>     let data = (message as? CustomMessage)?.customData
>     let name = UILabel()
>     name.font = .preferredFont(forTextStyle: .headline)
>     name.text = data?["name"] as? String ?? "Contact"
>     let phone = UILabel()
>     phone.font = .preferredFont(forTextStyle: .subheadline)
>     phone.text = data?["phone"] as? String
>
>     let card = UIStackView(arrangedSubviews: [name, phone])
>     card.axis = .vertical
>     card.spacing = 2
>     card.isLayoutMarginsRelativeArrangement = true
>     card.layoutMargins = UIEdgeInsets(top: 8, left: 12, bottom: 8, right: 12)
>     return card
> })
>
> let request = MessagesRequest.MessageRequestBuilder()
>     .set(types: MessageListStore.defaultMessagesTypes + ["contact"])
>     .set(categories: MessageListStore.defaultMessagesCategories)
>     .set(limit: 30)
>     .hideReplies(hide: true)
>
> messageList
>     .set(messagesRequestBuilder: request)
>     .add(templates: [contact])
>     .set(user: user)
> ```

> [!NOTE]
>
> The request builder replaces the Kit's request whole. The list adds the user or group; set
> the types, categories, page size, `hideReplies` and — for a thread — the parent message id
> yourself. Live messages are filtered by the same types, so a type missing here never shows.

## Core Concepts

### The key is `category` + `type`

A message is matched to a factory or template by its category and type — the SDK's
`message` / `text`, `custom` / `extension_poll`, or `custom` / your own type. One is kept per
kind, and the **last registered wins**, so registering one for a built-in kind replaces the
Kit's bubble for that kind.

> [tab] SwiftUI
>
> The key is the factory's `kind`, a `MessageKind`. The built-in kinds are constants —
> `.text`, `.image`, `.video`, `.audio`, `.voiceNote`, `.file`, `.sticker`, `.poll`, `.meeting`,
> `.document`, `.whiteboard`, `.card`, `.aiAssistant`, `.groupAction`, `.audioCall`, `.videoCall`.
> A voice note is its own kind, `.voiceNote`, separate from `.audio`.

> [tab] UIKit
>
> The key is the template's `category` and `type` strings; its `kind` property is the
> `MessageKind` built from them. A `message` / `audio` template draws voice notes too.

A message with no factory or template of yours draws with the Kit's built-in bubble. A kind
that nothing draws shows "Unsupported: *category\_type*" — never a blank row. A **deleted**
message always draws the built-in "This message was deleted", whatever you register for its
kind.

### What each slot receives

> [tab] SwiftUI
>
> Every slot receives the message as the Kit's value type, `ChatMessage`, and its
> `MessageAlignment` — `.incoming`, `.outgoing` or `.centred`. A custom message's `customData`
> is `message.custom?.data`, a dictionary of `SuggestionItem.DataValue` (`.string`, `.int`,
> `.double`, `.bool`, `.array`, `.object`, `.null`). The resolved bubble style is in the
> environment as `\.cometChatMessageBubbleStyle`.
>
> There is no create/bind split: the list asks the factory for a view each time it draws the
> row, and SwiftUI diffs it. A factory must be `Sendable` — a struct with `Sendable` stored
> properties is.

> [tab] UIKit
>
> Every closure receives three arguments: the SDK's `BaseMessage?` (cast it to
> `CustomMessage`, `TextMessage` …), its `MessageBubbleAlignment` — `.left`, `.right` or
> `.center` — and the view controller the list is in, found from the responder chain.
>
> The closures run **each time a row is configured**, including when a cell is reused, and the
> view they return is installed in that row. Return a new view each time and keep no per-message
> state outside it.

### Content vs the whole bubble

> [tab] SwiftUI
>
> | You implement | You get |
> | - | - |
> | `content` *(required)* | the payload, inside the Kit's bubble — avatar, name, quote, status line, reactions and "N replies" stay |
> | `bubbleView` | the **whole row**; no other member is asked |
>
> Because `content` is required, a factory for a built-in kind replaces the built-in content.
> To keep it and change only one region, delegate `content` to the built-in factory:
>
> ```swift theme={null}
> struct PinnedStarTextFactory: BubbleFactory {
>     let base = TextBubbleFactory()
>     var kind: MessageKind { .text }
>
>     @MainActor func content(_ message: ChatMessage, _ alignment: MessageAlignment) -> AnyView {
>         base.content(message, alignment)
>     }
>
>     @MainActor func footerView(_ message: ChatMessage, _ alignment: MessageAlignment) -> AnyView? {
>         message.isPinned ? AnyView(Image(systemName: "star.fill").font(.caption2)) : nil
>     }
> }
> ```

> [tab] UIKit
>
> | You set | You get |
> | - | - |
> | `contentView` | the payload, inside the Kit's bubble — avatar, name, quote, status line, reactions and "N replies" stay |
> | `bubbleView` | the **whole row** — header, bubble and footer; no other closure is asked |
>
> Every closure is optional. A closure that returns `nil`, or no closure, keeps the built-in
> view for that region — so a template with only a `footerView` keeps the built-in content:
>
> ```swift theme={null}
> let pinnedStar = CometChatMessageTemplate(category: "message", type: "text", footerView: { message, _, _ in
>     guard message?.pinnedAt ?? 0 > 0 else { return nil }
>     return UIImageView(image: UIImage(systemName: "star.fill"))
> })
> messageList.add(templates: [pinnedStar])
> ```

Registering one for a centred kind — `.groupAction`, `.audioCall`, `.videoCall` — gives
those rows the full bubble chrome: name, status line and reactions.

## Optional view slots

Every slot is optional. Leave it out, or return `nil`, to keep the Kit's view for that region.

| Region | SwiftUI `BubbleFactory` | UIKit `CometChatMessageTemplate` |
| - | - | - |
| The avatar column | `leadingView` | `leadingView` — a property, not an `init` argument |
| The sender's name above the bubble | `headerView` | `headerView` |
| The quoted message | `replyView` | `replyView` |
| Under the payload, inside the bubble — the moderation notice | `bottomView` | `bottomView` |
| The time and receipt line | `statusInfoView` | `statusInfoView` |
| "N replies" under the bubble | `threadView` | `threadView` — a property, not an `init` argument |
| The reactions under the bubble | `footerView` | `footerView` |
| The bubble's container style | `style(for:)` | — use the list's style |
| The long-press menu for this kind | — use the list's options | `options` |

> [tab] SwiftUI
>
> `style(for:)` is asked per alignment and wins over the list's bubble styles:
>
> ```swift theme={null}
> struct AnnouncementFactory: BubbleFactory {
>     let base = TextBubbleFactory()
>     var kind: MessageKind { .text }
>
>     @MainActor func content(_ message: ChatMessage, _ alignment: MessageAlignment) -> AnyView {
>         base.content(message, alignment)
>     }
>
>     @MainActor func headerView(_ message: ChatMessage, _ alignment: MessageAlignment) -> AnyView? {
>         AnyView(Text(message.sender.name).font(.caption.bold()).foregroundStyle(.indigo))
>     }
>
>     func style(for alignment: MessageAlignment) -> MessageBubbleStyle? {
>         alignment == .incoming ? MessageBubbleStyle(backgroundColor: .indigo.opacity(0.12), cornerRadius: 16) : nil
>     }
> }
> ```
>
> The message list's own slots — `leadingView:`, `headerView:`, `contentView:` … — apply to
> every kind and **outrank** a factory's.

> [tab] UIKit
>
> `leadingView` and `threadView` are set as properties. `options`, when it returns non-`nil`,
> replaces the menu for this kind; the list's `set(options:)` still outranks it. Handle the
> option in `set(onMessageOptionClick:)`:
>
> ```swift theme={null}
> let text = CometChatMessageTemplate(category: "message", type: "text")
> text.leadingView = { _, _, _ in
>     let badge = UIImageView(image: UIImage(systemName: "person.crop.circle.fill"))
>     badge.tintColor = .systemIndigo
>     return badge
> }
> text.options = { _, _, _ in
>     [CometChatMessageOption(id: "copy-link", title: "Copy link", icon: UIImage(systemName: "link"))]
> }
>
> messageList
>     .add(templates: [text])
>     .set(onMessageOptionClick: { message, id, _ in
>         if id == "copy-link" { UIPasteboard.general.string = (message as? TextMessage)?.text }
>     })
> ```
>
> A template's `options` is not filtered by the list's `hide…Option` flags.

## Bubbles outside the list

The thread header, Message Information and Pinned Messages draw messages with the same
bubbles. Hand them your factories or templates too.

> [tab] SwiftUI
>
> * `CometChatMessageInformation`, opened from the list's Info option, gets the list's
>   `bubbleFactories` automatically.
> * `CometChatThreadHeader(parentMessage:bubbleFactories:)` and
>   `CometChatPinnedMessages(user:group:bubbleFactories:)` take them as an argument.
> * `CometChatMessageBubble(message:alignment:factory:)` draws one message anywhere.
>
> ```swift theme={null}
> CometChatThreadHeader(parentMessage: parentMessage, bubbleFactories: [ContactBubbleFactory()])
> ```

> [tab] UIKit
>
> * `CometChatMessageInformation`, opened from the list's Info option, gets the list's templates
>   automatically.
> * `CometChatThreadHeader` takes them with `set(templates:)` or `add(template:)`.
> * `CometChatPinnedMessages` draws the built-in bubbles only; it takes no templates.
>
> ```swift theme={null}
> let contact = CometChatMessageTemplate(category: "custom", type: "contact", contentView: { message, _, _ in
>     let name = UILabel()
>     name.text = (message as? CustomMessage)?.customData?["name"] as? String ?? "Contact"
>     return name
> })
>
> let threadHeader = CometChatThreadHeader()
> threadHeader.set(templates: [contact])
> threadHeader.set(parentMessage: threadParent)
> ```

## Creating a new custom message type

1. **Send** the message as a `CustomMessage` with your own type. Send it through the Kit —
   not `CometChat.sendCustomMessage` — so the Kit's `messageSent` event goes out with it.
2. **Draw** it with a `BubbleFactory` (SwiftUI) or `CometChatMessageTemplate` (UIKit) whose
   category is `custom` and whose type matches exactly.
3. **Fetch** it: add the type to the list's `messagesRequestBuilder`.
4. **Register** it on every screen that shows those messages — the list, and the thread header.

> [tab] SwiftUI
>
> ```swift theme={null}
> let card = CustomMessage(receiverUid: "UID", receiverType: .user,
>                          customData: ["name": "Ana Lima", "phone": "+55 11 5555-0100"], type: "contact")
> try await CometChatSession.sendCustomMessage(card)
> ```

> [tab] UIKit
>
> ```swift theme={null}
> let card = CustomMessage(receiverUid: "UID", receiverType: .user,
>                          customData: ["name": "Ana Lima", "phone": "+55 11 5555-0100"], type: "contact")
> sendCustomMessage(message: card) { result in
>     if case .failure(let error) = result { print(error) }
> }
> ```

See [Send a Message](https://www.cometchat.com/docs/sdk/ios/send-message.md) for custom messages in the SDK. The message
composer has no built-in way to send your type — add an attachment option or an auxiliary
button that sends it; see [Message Composer](https://www.cometchat.com/docs/ui-kit/ios/v6/message-composer.md).

## Next Steps

> [card] [Message List](https://www.cometchat.com/docs/ui-kit/ios/v6/message-list.md)
>
> Where bubbles are registered, and the list-wide view slots

> [card] [Message Bubble Styling](https://www.cometchat.com/docs/ui-kit/ios/v6/message-bubble-styling.md)
>
> Style bubbles without replacing views

> [card] [Threaded Messages Header](https://www.cometchat.com/docs/ui-kit/ios/v6/thread-header.md)
>
> The parent message, drawn with your bubbles

> [card] [Upgrading from v5](https://www.cometchat.com/docs/ui-kit/ios/v6/migrating-from-v5.md)
>
> v5 templates in v6, and what replaced the DataSource chain


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.