> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-ios-composer-trailing-buttons.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Compact Message Composer

> Configure CometChat iOS UI Kit Compact Message Composer with single-line input, rich text, attachments, mentions, stickers, and voice recording.

## Overview

`CometChatCompactMessageComposer` is a [Component](/ui-kit/ios/components-overview#components) that provides a compact, single-line message input designed for chat applications. It offers a streamlined interface with optional rich text formatting capabilities, supporting bold, italic, strikethrough, code, links, lists, and blockquotes.

Features such as Rich Text Formatting, Attachments, Message Editing, Mentions, Stickers, and Voice Recording are supported.

## Usage

### Integration

The following code snippet illustrates how you can directly incorporate the CompactMessageComposer component into your view.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    let compactComposer = CometChatCompactMessageComposer()
    compactComposer.set(user: user)
    compactComposer.set(controller: self)
    compactComposer.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(compactComposer)
    ```
  </Tab>
</Tabs>

<Note>
  To ensure that the `CometChatCompactMessageComposer` is properly configured, passing the controller is mandatory.

  ```swift theme={null}
  compactComposer.set(controller: self) // Passing the controller is required
  ```
</Note>

### Actions

[Actions](/ui-kit/ios/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs.

##### setOnSendButtonClick

The `set(onSendButtonClick:)` event gets activated when the send message button is clicked. It has a predefined function of sending messages entered in the composer. However, you can override this action with the following code snippet.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    compactComposer.set(onSendButtonClick: { message in
        // Your custom send handling
    })
    ```
  </Tab>
</Tabs>

***

##### setOnError

This action doesn't change the behavior of the component but rather listens for any errors that occur in the CompactMessageComposer component.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    compactComposer.set(onError: { error in
        // Your Exception Handling code
    })
    ```
  </Tab>
</Tabs>

***

##### setOnTextChangedListener

Function triggered whenever the message input's text value changes, enabling dynamic text handling.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    compactComposer.set(onTextChangedListener: { text in
        // Handle text change
    })
    ```
  </Tab>
</Tabs>

***

##### setAttachmentOptions

This action is triggered when the attachment button is clicked. You can override the default attachment sheet behavior with a custom implementation.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    compactComposer.set(attachmentOptions: { user, group, controller in
        // Return custom attachment actions
        return [CometChatMessageComposerAction]
    })
    ```
  </Tab>
</Tabs>

***

### Filters

CompactMessageComposer component does not have any available filters.

***

### Events

[Events](/ui-kit/ios/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed.

The CompactMessageComposer Component does not emit any events of its own.

***

## Customization

To fit your app's design requirements, you can customize the appearance of the CompactMessageComposer component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs.

### Style

Using Style you can customize the look and feel of the component in your app. These parameters typically control elements such as the color, size, shape, and fonts used within the component.

**Global level styling**

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    CometChatCompactMessageComposer.style.activeSendButtonBackgroundColor = UIColor(hex: "#F76808")
    CometChatCompactMessageComposer.style.attachmentImageTint = UIColor(hex: "#F76808")
    CometChatCompactMessageComposer.style.voiceRecordingImageTint = UIColor(hex: "#F76808")
    CometChatCompactMessageComposer.style.stickersImageTint = UIColor(hex: "#F76808")
    ```
  </Tab>
</Tabs>

**Instance level styling**

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    var customStyle = CompactMessageComposerStyle()
    customStyle.activeSendButtonBackgroundColor = UIColor(hex: "#F76808")
    customStyle.attachmentImageTint = UIColor(hex: "#F76808")
    customStyle.voiceRecordingImageTint = UIColor(hex: "#F76808")
    customStyle.stickersImageTint = UIColor(hex: "#F76808")

    let compactComposer = CometChatCompactMessageComposer()
    compactComposer.style = customStyle
    ```
  </Tab>
</Tabs>

The following properties are exposed by `CompactMessageComposerStyle`:

| Property                                 | Description                                             | Code                                                                              |
| ---------------------------------------- | ------------------------------------------------------- | --------------------------------------------------------------------------------- |
| backgroundColor                          | Background color of the composer container.             | `style.backgroundColor = CometChatTheme.backgroundColor03`                        |
| cornerRadius                             | Corner radius for the composer container.               | `style.cornerRadius = CometChatCornerStyle?`                                      |
| borderWidth                              | Border width for the composer container.                | `style.borderWidth = 0`                                                           |
| borderColor                              | Border color for the composer container.                | `style.borderColor = .clear`                                                      |
| composeBoxBackgroundColor                | Background color for the compose box.                   | `style.composeBoxBackgroundColor = CometChatTheme.backgroundColor01`              |
| composeBoxBorderColor                    | Border color for the compose box.                       | `style.composeBoxBorderColor = CometChatTheme.borderColorDefault`                 |
| composeBoxBorderWidth                    | Border width for the compose box.                       | `style.composeBoxBorderWidth = 1`                                                 |
| composeBoxCornerRadius                   | Corner radius for the compose box.                      | `style.composeBoxCornerRadius = .init(cornerRadius: CometChatSpacing.Radius.r2)`  |
| composerSeparatorColor                   | Color for the separator in the compose box.             | `style.composerSeparatorColor = CometChatTheme.borderColorLight`                  |
| textFieldFont                            | Font for the input text field.                          | `style.textFieldFont = CometChatTypography.Body.regular`                          |
| textFieldColor                           | Text color for the input field.                         | `style.textFieldColor = CometChatTheme.textColorPrimary`                          |
| placeholderFont                          | Font for the placeholder text.                          | `style.placeholderFont = CometChatTypography.Body.regular`                        |
| placeholderColor                         | Color for the placeholder text.                         | `style.placeholderColor = CometChatTheme.textColorTertiary`                       |
| sendButtonImage                          | Icon for the send button.                               | `style.sendButtonImage = UIImage(named: "custom-send")`                           |
| sendButtonImageTint                      | Tint color for the send button image.                   | `style.sendButtonImageTint = CometChatTheme.white`                                |
| activeSendButtonBackgroundColor          | Background color for send button when active.           | `style.activeSendButtonBackgroundColor = CometChatTheme.primaryColor`             |
| inactiveSendButtonBackgroundColor        | Background color for send button when inactive.         | `style.inactiveSendButtonBackgroundColor = CometChatTheme.neutralColor300`        |
| attachmentImage                          | Icon for the attachment button.                         | `style.attachmentImage = UIImage(systemName: "plus.circle")`                      |
| attachmentImageTint                      | Tint color for the attachment image.                    | `style.attachmentImageTint = CometChatTheme.iconColorSecondary`                   |
| voiceRecordingImage                      | Icon for the voice recording button.                    | `style.voiceRecordingImage = UIImage(systemName: "mic")`                          |
| voiceRecordingImageTint                  | Tint color for the voice recording image.               | `style.voiceRecordingImageTint = CometChatTheme.iconColorSecondary`               |
| stickersImage                            | Icon for the stickers button.                           | `style.stickersImage = UIImage(named: "sticker-image")`                           |
| stickersImageTint                        | Tint color for the stickers image.                      | `style.stickersImageTint = CometChatTheme.iconColorSecondary`                     |
| stickersActiveImageTint                  | Tint color for the stickers image when active.          | `style.stickersActiveImageTint = CometChatTheme.primaryColor`                     |
| codeBlockBackgroundColor                 | Background color for code block mode.                   | `style.codeBlockBackgroundColor = UIColor(hex: "#F5F5F5")`                        |
| codeBlockBorderColor                     | Border color for code block mode.                       | `style.codeBlockBorderColor = UIColor(hex: "#E8E8E8")`                            |
| codeBlockBorderWidth                     | Border width for code block mode.                       | `style.codeBlockBorderWidth = 1`                                                  |
| previewTitleFont                         | Font for the title in the edit/reply preview.           | `style.previewTitleFont = CometChatTypography.Body.regular`                       |
| previewMessageFont                       | Font for the message text in the edit/reply preview.    | `style.previewMessageFont = CometChatTypography.Caption1.regular`                 |
| previewTitleColor                        | Text color for the title in the edit/reply preview.     | `style.previewTitleColor = CometChatTheme.textColorPrimary`                       |
| previewMessageColor                      | Text color for the message in the edit/reply preview.   | `style.previewMessageColor = CometChatTheme.textColorSecondary`                   |
| previewBackgroundColor                   | Background color for the edit/reply preview.            | `style.previewBackgroundColor = CometChatTheme.backgroundColor03`                 |
| previewCloseIcon                         | Icon for closing the edit/reply preview.                | `style.previewCloseIcon = UIImage(systemName: "xmark")`                           |
| previewCloseIconTint                     | Tint color for the close icon in the preview.           | `style.previewCloseIconTint = CometChatTheme.iconColorHighlight`                  |
| infoIcon                                 | Icon for the mention limit info banner.                 | `style.infoIcon = UIImage(systemName: "info.circle")`                             |
| infoIconTint                             | Tint color for the info icon.                           | `style.infoIconTint = CometChatTheme.errorColor`                                  |
| infoTextColor                            | Text color for the info text.                           | `style.infoTextColor = CometChatTheme.errorColor`                                 |
| infoTextFont                             | Font for the info text.                                 | `style.infoTextFont = CometChatTypography.Caption1.regular`                       |
| infoBackgroundColor                      | Background color for the info section.                  | `style.infoBackgroundColor = CometChatTheme.backgroundColor02`                    |
| richTextToolbarStyle                     | Style configuration for the rich text toolbar.          | `style.richTextToolbarStyle = RichTextToolbarStyle()`                             |
| agenticSendButtonImage                   | Icon for the send button in agentic mode.               | `style.agenticSendButtonImage = UIImage(systemName: "arrow.up")`                  |
| agenticSendButtonImageTint               | Tint color for the agentic send button image.           | `style.agenticSendButtonImageTint = CometChatTheme.neutralColor50`                |
| agenticActiveSendButtonBackgroundColor   | Background color for agentic send button when active.   | `style.agenticActiveSendButtonBackgroundColor = CometChatTheme.neutralColor900`   |
| agenticInactiveSendButtonBackgroundColor | Background color for agentic send button when inactive. | `style.agenticInactiveSendButtonBackgroundColor = CometChatTheme.neutralColor300` |

***

### Functionality

These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements.

Below is a list of customizations along with corresponding code snippets:

| Property                               | Description                                                                                                                                      | Code                                           |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------- |
| User                                   | Used to pass user object of which header specific details will be shown.                                                                         | `set(user: User)`                              |
| Group                                  | Used to pass group object of which header specific details will be shown.                                                                        | `set(group: Group)`                            |
| setParentMessageId                     | Sets the parent message ID for threaded replies.                                                                                                 | `set(parentMessageId: Int)`                    |
| setPlaceholder                         | Sets the placeholder text for the input field.                                                                                                   | `set(placeholder: "Type a message...")`        |
| setMaxLines                            | Maximum lines allowed to increase in the input field.                                                                                            | `set(maxLines: Int)`                           |
| setTextFormatter                       | Assigns the list of text formatters (e.g., mentions).                                                                                            | `set(textFormatter: [CometChatTextFormatter])` |
| setEnableRichTextFormatting            | Master switch to enable or disable rich text formatting (bold, italic, etc.). Default `true`.                                                    | `enableRichTextFormatting = true`              |
| setRichTextFormattingOptionsVisibility | Controls the visibility of the rich text formatting toolbar. Default `true`.                                                                     | `showRichTextFormattingOptions = true`         |
| setDisableTypingEvents                 | Used to disable/enable typing events, default false.                                                                                             | `disable(typingEvents: true)`                  |
| setDisableSoundForMessages             | Used to toggle sound for outgoing messages.                                                                                                      | `disable(soundForMessages: true)`              |
| setCustomSoundForMessages              | Used to give custom sounds to outgoing messages.                                                                                                 | `customSoundForMessage = URL`                  |
| setDisableMentions                     | Sets whether mentions in text should be disabled. Removes any formatters that are instances of `CometChatMentionsFormatter`.                     | `disable(mentions: true)`                      |
| setAttachmentButtonVisibility          | Hides the attachment button in the composer.                                                                                                     | `hideAttachmentButton = true`                  |
| setVoiceRecordingButtonVisibility      | Hides the voice recording button in the composer.                                                                                                | `hideVoiceRecordingButton = true`              |
| setStickerButtonVisibility             | Hides the sticker button in the composer.                                                                                                        | `hideStickersButton = true`                    |
| setSendButtonVisibility                | Hides the send button in the composer.                                                                                                           | `hideSendButton = true`                        |
| setEnableMultipleAttachments           | Multi-select attachment picking with a preview tray. Default `true`; `false` reverts to the legacy single-attachment, send-immediately behavior. | `enableMultipleAttachments = true`             |

***

## Multiple Attachments

The compact composer supports sending several attachments in one go. Tapping a media or file option opens a multi-select picker; the picks are staged in an **attachment tray** above the input box, upload immediately, and are sent together when the user taps send.

**How it works:**

* **Multi-select picking** — the photo/video picker and the document picker both allow selecting multiple items, capped to the app's per-message limit. Camera captures and audio files stage into the same tray.
* **Attachment tray** — each staged file shows as a tile (thumbnail for media, chip for files/audio) with a live upload progress ring, a ✕ to cancel or remove, and tap-to-retry on network failure.
* **Upload before send** — files upload as soon as they are staged; the send button stays disabled until every upload finishes. Text typed in the composer becomes the **caption** of the batch, with rich text formatting preserved.
* **One message per attachment type** — a mixed pick is split into separate messages in a fixed order (images → videos → audios → files) that render as grouped bubbles in the message list.
* **Clipboard paste** — images, videos, documents and audio files copied to the clipboard can be pasted straight into the composer and stage into the tray.
* **Voice notes stay standalone** — a mic recording always sends immediately as its own message and is never staged. The mic button hides while attachments are staged and returns when the tray empties.
* Attachments cannot be added while **editing** a message; the attachment button is disabled for the duration of the edit. Editing a media message edits its caption only.

### Limits and Validation

Limits are governed by the app's server settings (CometChat dashboard) — the composer reads them at runtime and they cannot be overridden client-side:

| Limit             | Setting                          | Behavior on violation                                                                                   |
| ----------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------- |
| Files per message | `file.count.max` (default 10)    | Picker selection is capped; overflow picks are dropped with a "You can attach up to N files." snack bar |
| Per-file size     | `file.size.max` (default 100 MB) | The file stages as a red, non-retryable error tile; sending is blocked until it is removed              |
| File type         | Server-side validation           | The upload is refused by the server and the file becomes a red, non-retryable error tile                |

Tapping an error tile shows a snack bar with the reason ("File exceeds N MB.", "This file type isn't allowed."). The snack bar's appearance is themable through `CometChatErrorStateStyle`:

```swift theme={null}
CometChatErrorState.defaultStyle.backgroundColor = .systemRed
CometChatErrorState.defaultStyle.cornerRadius = 12
```

### Disabling Multiple Attachments

Set `enableMultipleAttachments` to `false` to restore the legacy behavior — single-item pickers that send immediately with no tray:

```swift theme={null}
compactComposer.enableMultipleAttachments = false
```

This is composer-side only: received multi-attachment messages still render with the grouped bubbles (see [Message List](/ui-kit/ios/message-list)).

***

## Rich Text Formatting

The CompactMessageComposer includes a built-in rich text editor. `enableRichTextFormatting` and `showRichTextFormattingOptions` are `true` by default, so rich text formatting and the formatting toolbar are enabled out of the box.

* `enableRichTextFormatting` — Master switch that activates formatting. When set to `false`, even manually typed markdown syntax like `**text**` will be sent as plain text.
* `showRichTextFormattingOptions` — Controls the visibility of the formatting toolbar below the input field.

### Supported Format Types

| Format        | Description             | Markdown Syntax |
| ------------- | ----------------------- | --------------- |
| Bold          | Makes text bold         | `**text**`      |
| Italic        | Makes text italic       | `*text*`        |
| Underline     | Underlines text         | `<u>text</u>`   |
| Strikethrough | Strikes through text    | `~~text~~`      |
| Inline Code   | Formats as inline code  | `` `code` ``    |
| Code Block    | Creates a code block    | ` ```code``` `  |
| Blockquote    | Creates a blockquote    | `> text`        |
| Numbered List | Creates a numbered list | `1. item`       |
| Bullet List   | Creates a bullet list   | `- item`        |
| Link          | Creates a hyperlink     | `[text](url)`   |

### Configuration

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    // Disable rich text formatting
    compactComposer.enableRichTextFormatting = false

    // Hide the formatting toolbar
    compactComposer.showRichTextFormattingOptions = false
    ```
  </Tab>
</Tabs>

| enableRichTextFormatting | showRichTextFormattingOptions | Result                                               |
| ------------------------ | ----------------------------- | ---------------------------------------------------- |
| true (default)           | true (default)                | Toolbar visible below input, full formatting support |
| true                     | false                         | No toolbar, markdown syntax is still parsed on send  |
| false                    | —                             | Plain text, no formatting                            |

***

### RichTextToolbarStyle

**Global level styling**

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    CometChatCompactMessageComposer.style.richTextToolbarStyle.backgroundColor = UIColor(hex: "#F5F5F5")
    CometChatCompactMessageComposer.style.richTextToolbarStyle.iconTintColor = UIColor(hex: "#666666")
    CometChatCompactMessageComposer.style.richTextToolbarStyle.activeIconTintColor = UIColor(hex: "#F76808")
    CometChatCompactMessageComposer.style.richTextToolbarStyle.activeButtonBackgroundColor = UIColor(hex: "#FFF0E6")
    ```
  </Tab>
</Tabs>

The following properties are exposed by `RichTextToolbarStyle`:

| Property                    | Description                            | Code                                                                                |
| --------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------- |
| backgroundColor             | Background color of the toolbar.       | `toolbarStyle.backgroundColor = CometChatTheme.backgroundColor02`                   |
| borderColor                 | Border color of the toolbar.           | `toolbarStyle.borderColor = CometChatTheme.borderColorLight`                        |
| buttonSize                  | Size of format buttons.                | `toolbarStyle.buttonSize = 30`                                                      |
| buttonSpacing               | Spacing between format buttons.        | `toolbarStyle.buttonSpacing = CometChatSpacing.Spacing.s2`                          |
| iconTintColor               | Tint color for inactive format icons.  | `toolbarStyle.iconTintColor = CometChatTheme.iconColorSecondary`                    |
| activeIconTintColor         | Tint color for active format icons.    | `toolbarStyle.activeIconTintColor = CometChatTheme.primaryColor`                    |
| buttonBackgroundColor       | Background color for inactive buttons. | `toolbarStyle.buttonBackgroundColor = .clear`                                       |
| activeButtonBackgroundColor | Background color for active buttons.   | `toolbarStyle.activeButtonBackgroundColor = CometChatTheme.extendedPrimaryColor100` |

***

### Trailing toolbar actions

`set(richTextToolbarActions:)` appends your own buttons at the trailing end of the built-in toolbar — after the format buttons, separated by a divider — without replacing the toolbar. It takes the same closure shape as `set(attachmentOptions:)`, receiving the current `User?` and `Group?`, and returns a list of `CometChatRichTextToolbarAction` items.

| Property             | Type                               | Description                                                                                                                                |
| -------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `id`                 | `String`                           | Identifies the action, and looks the rendered button up in `CometChatRichTextToolbar.trailingActionButtons`.                               |
| `icon`               | `UIImage?`                         | The button glyph. Rendered as-is — apply `.withRenderingMode(.alwaysTemplate)` for `tint` or the toolbar's `iconTintColor` to take effect. |
| `onClick`            | `(CometChatComposerInput) -> Void` | Called on tap with a live handle onto the composer's input.                                                                                |
| `tint`               | `UIColor?`                         | Overrides `RichTextToolbarStyle.iconTintColor` when non-nil.                                                                               |
| `accessibilityLabel` | `String?`                          | VoiceOver label. Falls back to `id`, so a button is never unlabelled.                                                                      |

Each action's `onClick` receives a **`CometChatComposerInput`** — a live handle for reading and mutating the draft, so the composer stays the owner of the field:

| Member                                                                                                     | Description                                                                                                |
| ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `text: String`                                                                                             | The input's contents without attributes.                                                                   |
| `attributedText: NSAttributedString`                                                                       | The contents, including formatting attributes.                                                             |
| `selectedRange: NSRange`                                                                                   | The current selection, or a zero-length range at the caret.                                                |
| `hasSelection: Bool`                                                                                       | Whether text is selected, as opposed to a caret being placed.                                              |
| `typingAttributes: [NSAttributedString.Key: Any]`                                                          | Attributes the next typed character inherits — set this to format text typed next rather than a selection. |
| `mentionRanges: [NSRange]`                                                                                 | The ranges currently occupied by mentions.                                                                 |
| `attributes(at:)`                                                                                          | The attributes at a location, or empty if out of bounds.                                                   |
| `insertAtCaret(_:)`                                                                                        | Insert at the caret, replacing any selection; the caret lands after the inserted text.                     |
| `setAttributedText(_:preservingSelection:)`                                                                | Replace the contents, keeping the selection by default.                                                    |
| `setSelectedRange(_:)`                                                                                     | Move the caret or change the selection, clamped to the current length.                                     |
| `applyAttributes(_:to:protectingKitRuns:)` / `removeAttributes(_:from:protectingKitRuns:)`                 | Add or strip attributes over a range.                                                                      |
| `applyAttributesToSelection(_:protectingKitRuns:)` / `removeAttributesFromSelection(_:protectingKitRuns:)` | The same over the current selection; each returns whether there was a selection to act on.                 |
| `commit()`                                                                                                 | Resync the toolbar and send button partway through a long edit.                                            |

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    compactComposer.set(richTextToolbarActions: { user, group in
        [
            CometChatRichTextToolbarAction(
                id: "insert_greeting",
                icon: UIImage(systemName: "hand.wave")?.withRenderingMode(.alwaysTemplate),
                accessibilityLabel: "Greeting"
            ) { input in
                input.insertAtCaret(NSAttributedString(string: "Hello! "))
            }
        ]
    })
    ```
  </Tab>
</Tabs>

Actions are registered per composer instance, so a thread composer can offer a different set from the main one.

<Note>
  The trailing section lives **inside** the rich-text toolbar — it is not rendered when the toolbar is hidden (`showRichTextFormattingOptions = false`) or rich text is disabled (`enableRichTextFormatting = false`).

  The `CometChatComposerInput` is valid only for the duration of the `onClick` call; don't retain it. The action itself is retained by the toolbar, so capture `self` weakly.

  The composer serializes to markdown on send. The built-in formats survive, and so does text colour — see [Colour that survives send](#colour-that-survives-send). Any other attribute you apply is composer-local: markdown has no representation for it, so it is dropped from the sent message. Use those for affordances that are meant to be transient, such as marking a range while the action's own picker or sheet is open.
</Note>

Mutations apply immediately, but composer state that derives from the text — the toolbar's active formats and the send button — resyncs once when `onClick` returns rather than per mutation, so a multi-step edit resyncs once. Call `commit()` to resync earlier.

#### Leaving Kit-owned runs alone

An action that restyles a range will happily run over a mention or a link, which the Kit repaints on its own schedule — so your attribute is reverted on the next repaint anyway, and removing one of the Kit's attributes deletes it rather than restoring the Kit's value.

The mutating methods therefore take `protectingKitRuns`, which defaults to `true`. With it on, the following are carved out of the target range and left untouched:

* mentions
* links, including a URL still being typed
* inline code and code blocks, and any monospaced run
* fully transparent runs, so an action cannot repaint hidden text into view

Pass `protectingKitRuns: false` to opt out and write over the whole range. To make a narrower decision yourself, read `mentionRanges` — the ranges are read at call time, so re-read them after a mutation rather than caching, as they shift with the text. Note that `mentionRanges` covers mentions only; the other carve-outs above have no public accessor.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    CometChatRichTextToolbarAction(
        id: "red_text",
        icon: UIImage(systemName: "paintpalette")?.withRenderingMode(.alwaysTemplate),
        accessibilityLabel: "Red text"
    ) { input in
        // Colouring applies to a selection; with only a caret there is nothing
        // to restyle, so leave the text alone rather than guessing at a range.
        guard input.hasSelection else { return }

        // Kit-owned runs are protected by default and keep their own styling.
        input.applyAttributesToSelection([
            .foregroundColor: UIColor.systemRed,
            RichTextFormatterManager.textColorKey: UIColor.systemRed
        ])
    }
    ```
  </Tab>
</Tabs>

#### Colour that survives send

Text colour is the one value-carrying style with a wire representation: the composer serializes it as `<color=#rrggbb>…</color>`, and the message bubble parses it back. Colour therefore reaches the recipient, unlike other attributes you might apply.

Setting `.foregroundColor` on its own is not enough. That key is written by six different things — mentions, links, inline code, code blocks, ordinary text and the user — so it records nothing about *who* set it. `RichTextFormatterManager.textColorKey` is the marker that identifies a run the user deliberately coloured, and it is what the serializer looks for. Always write and remove the two together.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    // Applies colour, and marks the run so it survives send.
    input.applyAttributesToSelection([
        .foregroundColor: UIColor.systemRed,
        RichTextFormatterManager.textColorKey: UIColor.systemRed
    ])

    // Clearing colour removes both keys; the text falls back to the
    // composer's own colour rather than to a value hard-coded here.
    input.removeAttributesFromSelection([
        .foregroundColor,
        RichTextFormatterManager.textColorKey
    ])
    ```
  </Tab>
</Tabs>

<Note>
  Use opaque colours. Only `#rgb` and `#rrggbb` are valid on the wire — eight-digit `#rrggbbaa` is rejected deliberately, since a fully transparent run would be an invisible message.

  A translucent `UIColor` is **not** rejected locally: it renders in the composer, then is dropped on send, because a colour with alpha below 1 has no wire representation. That is the silent loss this section exists to prevent, so pass a fully opaque colour.
</Note>

The UI Kit ships no colour button of its own: the wire format and the serializer are provided, the button is yours. That is what the trailing-actions slot is for.

***

## Advanced

For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component.

### setTextFormatters

Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel check out [CometChatMentionsFormatter](/ui-kit/ios/mentions-formatter-guide)

**Example**

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    let composerTextStyle = MentionTextStyle()
        .set(textBackgroundColor: .white)
        .set(textColor: UIColor.black)
        .set(textFont: UIFont.systemFont(ofSize: 18, weight: .heavy))
        .set(loggedInUserTextColor: UIColor.systemTeal)
        .set(loggedInUserTextFont: UIFont.systemFont(ofSize: 18, weight: .bold))

    let customMentionFormatter = CometChatMentionsFormatter()
        .set(composerTextStyle: composerTextStyle)

    let compactComposer = CometChatCompactMessageComposer()
    compactComposer.set(textFormatter: [customMentionFormatter])
    ```
  </Tab>
</Tabs>

***

### setAttachmentOptions

By using `set(attachmentOptions:)`, you can set a list of custom `CometChatMessageComposerAction` for the CompactMessageComposer Component. This will override the existing list of `CometChatMessageComposerAction`.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    compactComposer.set(attachmentOptions: { user, group, controller in
        return [CometChatMessageComposerAction]
    })
    ```
  </Tab>
</Tabs>

**Example**

In this example, we are overriding the existing MessageComposerActions List with custom actions.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    let compactComposer = CometChatCompactMessageComposer()

    compactComposer.set(attachmentOptions: { user, group, controller in
        let action1 = CometChatMessageComposerAction(
            id: "customAction1",
            text: "Custom Option 1",
            startIcon: UIImage(systemName: "camera"),
            startIconTint: .black,
            textColor: .black,
            onActionClick: {
                print("Custom Option 1 clicked!")
            }
        )

        let action2 = CometChatMessageComposerAction(
            id: "customAction2",
            text: "Custom Option 2",
            startIcon: UIImage(systemName: "doc"),
            startIconTint: .black,
            textColor: .black,
            onActionClick: {
                print("Custom Option 2 clicked!")
            }
        )

        return [action1, action2]
    })
    ```
  </Tab>
</Tabs>

***

### Edit & Reply Mode

The CompactMessageComposer supports editing and replying to messages. You can programmatically put the composer into edit or reply mode.

**Edit a message**

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    compactComposer.edit(message: textMessage)
    ```
  </Tab>
</Tabs>

**Reply to a message**

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    compactComposer.reply(message: baseMessage)
    ```
  </Tab>
</Tabs>

**Preview a message with a specific mode**

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    compactComposer.preview(message: baseMessage, mode: .edit)
    // or
    compactComposer.preview(message: baseMessage, mode: .reply)
    ```
  </Tab>
</Tabs>

***

### Complete Integration Example

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    import UIKit
    import CometChatUIKitSwift

    class ChatViewController: UIViewController {
        var user: User?

        override func viewDidLoad() {
            super.viewDidLoad()
            setupComposer()
        }

        private func setupComposer() {
            guard let user = user else { return }

            let compactComposer = CometChatCompactMessageComposer()
            compactComposer.set(user: user)
            compactComposer.set(controller: self)

            // Customize
            compactComposer.set(placeholder: "Type a message...")
            compactComposer.disable(typingEvents: false)

            // Callbacks
            compactComposer.set(onSendButtonClick: { message in
                print("Message sent: \(message)")
            })

            compactComposer.set(onError: { error in
                print("Error: \(error.errorDescription)")
            })

            // Layout
            compactComposer.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview(compactComposer)

            NSLayoutConstraint.activate([
                compactComposer.leadingAnchor.constraint(equalTo: view.leadingAnchor),
                compactComposer.trailingAnchor.constraint(equalTo: view.trailingAnchor),
                compactComposer.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
            ])
        }
    }
    ```
  </Tab>
</Tabs>
