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

# Threaded Messages Header

> Configure CometChat iOS UI Kit threaded message headers with parent message context, reply lists, composer layout, and back actions.

The `CometChatThreadedMessageHeader` component displays the header for threaded message conversations showing parent message info. By default, the parent message appears at the top, the message composer is at the bottom, and a message list containing all replies is displayed between them.

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-docs-rn-guide-message-privately/NN4EdpOU3viwWMb_/images/0a425996-threaded-conversation-bb63b71df514c0eec680ffda196473de.png?fit=max&auto=format&n=NN4EdpOU3viwWMb_&q=85&s=e88b39203551e558f8be44ca46d8fd49" width="1440" height="1128" data-path="images/0a425996-threaded-conversation-bb63b71df514c0eec680ffda196473de.png" />
</Frame>

<Accordion title="AI Integration Quick Reference">
  ```json theme={null}
  {
    "component": "CometChatThreadedMessageHeader",
    "package": "CometChatUIKitSwift",
    "import": "import CometChatUIKitSwift\nimport CometChatSDK",
    "description": "Displays the header for threaded message conversations showing parent message info",
    "inherits": "UIView",
    "primaryOutput": {
      "callback": "onBack",
      "type": "() -> Void"
    },
    "props": {
      "data": {
        "parentMessage": { "type": "BaseMessage", "required": true }
      },
      "callbacks": {
        "onBack": "() -> Void"
      }
    },
    "events": [],
    "sdkListeners": [],
    "compositionExample": {
      "description": "ThreadedMessageHeader is used within ThreadedMessages component",
      "components": ["CometChatThreadedMessageHeader", "CometChatMessageList", "CometChatMessageComposer"],
      "flow": "User opens thread → sees parent message in header → views/sends replies below"
    }
  }
  ```
</Accordion>

| Field     | Value                            |
| --------- | -------------------------------- |
| Component | `CometChatThreadedMessageHeader` |
| Package   | `CometChatUIKitSwift`            |
| Inherits  | `UIView`                         |

***

ThreadedMessages is composed of the following components:

| Component                                       | Description                                                                                                        |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| [MessageList](/ui-kit/ios/message-list)         | CometChatMessageList is a component that displays a list of Messages                                               |
| [MessageComposer](/ui-kit/ios/message-composer) | CometChatMessageComposer is a component that helps in writing and editing of messages and also sending attachments |

***

## Usage

### Integration

Since `CometChatThreadedMessageHeader` is a view, you can add it to your view controller using the following code snippet:

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    let threadedMessage = CometChatThreadedMessageHeader()
    view.addSubview(threadedMessage)
    ```
  </Tab>
</Tabs>

<Note>
  Ensure to pass and present `threadedMessage`. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller.
</Note>

***

### Filters

Filters allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria for a more customized experience. Filters can be applied using RequestBuilders of Chat SDK.

ThreadedMessages does not have its own Filters. However, you can filter the messages list in ThreadedMessages Component using [MessageListConfiguration](#configuration).

**Example**

In this example, we are filtering messages and searching for messages that contain the keyword "payment":

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    // MARK: - Filter messages by search keyword
    let messageRequestBuilder = MessagesRequest.MessageRequestBuilder()
        .set(uid: "your UID")
        .set(searchKeyword: "sure")

    let messageList = CometChatMessageList()
    messageList.set(user: user)
    messageList.set(messagesRequestBuilder: messageRequestBuilder)
    ```
  </Tab>
</Tabs>

***

### Events

[Events](/ui-kit/ios/components-overview#events) are emitted by a Component. By using events, you can extend existing functionality. Being global events, they can be applied in multiple locations and are capable of being added or removed.

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

***

## Customization

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

***

### Style

`ThreadedMessageHeaderStyle` contains various properties which can be used to customize the UI of `CometChatThreadedMessageHeader`.

**Global Level Styling**

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    // MARK: - Apply global styling
    CometChatThreadedMessageHeader.style.backgroundColor = UIColor(hex: "#F76808")
    CometChatThreadedMessageHeader.style.dividerTintColor = UIColor(hex: "#F76808")
    CometChatThreadedMessageHeader.style.bubbleContainerBackgroundColor = UIColor(hex: "#F76808")
    ```
  </Tab>
</Tabs>

**Instance Level Styling**

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    // MARK: - Apply instance-level styling
    let customThreadedHeaderStyle = ThreadedMessageHeaderStyle()
    customThreadedHeaderStyle.backgroundColor = UIColor(hex: "#F76808")
    customThreadedHeaderStyle.dividerTintColor = UIColor(hex: "#F76808")
    customThreadedHeaderStyle.bubbleContainerBackgroundColor = UIColor(hex: "#F76808")
            
    let threadedMessage = CometChatThreadedMessageHeader()
    threadedMessage.style = customThreadedHeaderStyle
    ```
  </Tab>
</Tabs>

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-docs-rn-guide-message-privately/2SVOPiSpm0QEqRoz/images/e951c410-threaded-message-style-ec31c7ae27cceefa0f23b122cbcaccb4.png?fit=max&auto=format&n=2SVOPiSpm0QEqRoz&q=85&s=4a206a97a6924ebc1e9921a3c48a2c25" width="1280" height="329" data-path="images/e951c410-threaded-message-style-ec31c7ae27cceefa0f23b122cbcaccb4.png" />
</Frame>

List of properties available for configuring in ThreadedMessagesStyle:

| Property                          | Description                                | Code                                                                                             |
| --------------------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------ |
| Background Color                  | Background color for the header.           | `CometChatThreadedMessageHeader.style.backgroundColor = CometChatTheme.backgroundColor03`        |
| Border Color                      | Border color for the header.               | `CometChatThreadedMessageHeader.style.borderColor = UIColor.clear`                               |
| Border Width                      | Border width for the header.               | `CometChatThreadedMessageHeader.style.borderWith = 0`                                            |
| Corner Radius                     | Corner radius for the header.              | `CometChatThreadedMessageHeader.style.cornerRadius = CometChatCornerStyle?`                      |
| Bubble Container Background Color | Background color for the bubble container. | `CometChatThreadedMessageHeader.style.bubbleContainerBackgroundColor = UIColor.clear`            |
| Bubble Container Border Color     | Border color for the bubble container.     | `CometChatThreadedMessageHeader.style.bubbleContainerBorderColor = UIColor.clear`                |
| Bubble Container Border Width     | Border width for the bubble container.     | `CometChatThreadedMessageHeader.style.bubbleContainerBorderWidth = 0`                            |
| Bubble Container Corner Radius    | Corner radius for the bubble container.    | `CometChatThreadedMessageHeader.style.bubbleContainerCornerRadius = CometChatCornerStyle?`       |
| Divider Tint Color                | Tint color for the divider.                | `CometChatThreadedMessageHeader.style.dividerTintColor = CometChatTheme.extendedPrimaryColor100` |
| Count Text Color                  | Text color for the message count text.     | `CometChatThreadedMessageHeader.style.countTextColor = CometChatTheme.textColorSecondary`        |
| Count Text Font                   | Font for the message count text.           | `CometChatThreadedMessageHeader.style.countTextFont = CometChatTypography.Body.regular`          |

***

### 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 set maximum lines the text area will show before scrolling in the composer, edit a message, add header view and footer view to the composer, and more.

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

| Property            | Description                                            | Code                              |
| ------------------- | ------------------------------------------------------ | --------------------------------- |
| hideReplyCount      | Hides the reply count for threaded messages.           | `hideReplyCount = true`           |
| hideReplyCountBar   | Hides the reply count bar in the thread.               | `hideReplyCountBar = true`        |
| hideReceipts        | Hides read and delivery receipts for messages.         | `hideReceipts = true`             |
| hideAvatar          | Hides the avatar in the threaded message view.         | `hideAvatar = true`               |
| setMaxHeight        | Sets the maximum height for the threaded message view. | `setMaxHeight(300)`               |
| setMessageAlignment | Sets the alignment of messages (e.g., left or right).  | `setMessageAlignment(.right)`     |
| setParentMessage    | Sets the parent message for the threaded conversation. | `setParentMessage(parentMessage)` |

***

### 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.

#### SetDatePattern

You can modify the date pattern to your requirement using `.set(datePattern:)`. This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String.

**Example**

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    // MARK: - Custom date pattern
    let threadedMessageHeader = CometChatThreadedMessageHeader()
    threadedMessageHeader.set(datePattern: { timestamp in
        guard let timestamp = timestamp else {
            return ""
        }
        let date = Date(timeIntervalSince1970: TimeInterval(timestamp / 1000))
        let formatter = DateFormatter()
        formatter.dateFormat = "dd-MM-yyyy"
        return formatter.string(from: date)
    })
    ```
  </Tab>
</Tabs>

***

#### SetTextFormatters

This functionality dynamically assigns a list of text formatters. If a custom list is provided, it uses that list. Otherwise, it gracefully falls back to the default text formatters retrieved from the data source for seamless integration.

**Example**

This code customizes a CometChat text formatter to identify and style the word "sure", with handling options for interactions like string search, scrolling, and item clicks. The custom formatter is then applied to CometChat messages.

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    // MARK: - Apply custom text formatter
    let myCustomTextFormatter = MyCustomTextFormatter(trackingCharacter: "#")

    let threadedMessageHeader = CometChatThreadedMessageHeader()
        .set(user: user)
        .set(textFormatter: [myCustomTextFormatter])
    ```
  </Tab>
</Tabs>

**Demonstration:**

<Tabs>
  <Tab title="MyCustomTextFormatter">
    ```swift lines theme={null}
    import Foundation
    import CometChatSDK
    import CometChatUIKitSwift

    class MyCustomTextFormatter: CometChatTextFormatter {
        
        // MARK: - Regex Pattern
        override func getRegex() -> String {
            return "(\\bsure\\b)"
        }

        // MARK: - Tracking Character
        override func getTrackingCharacter() -> Character {
            return "#"
        }

        // MARK: - Search
        override func search(string: String, suggestedItems: ((_: [SuggestionItem]) -> ())? = nil) {
            // This function would call an API or perform a local search
            // For now, it does nothing
        }

        // MARK: - Pagination
        override func onScrollToBottom(suggestionItemList: [SuggestionItem], listItem: ((_: [SuggestionItem]) -> ())?) {
            // This function would call the next page of an API
            // For now, it does nothing
        }

        // MARK: - Item Selection
        override func onItemClick(suggestedItem: SuggestionItem, user: User?, group: Group?) {
            // Do something with the clicked item
        }

        // MARK: - Pre-Send Processing
        override func handlePreMessageSend(baseMessage: BaseMessage, suggestionItemList: [SuggestionItem]) {
            // This function would modify the message before it's sent
            // For now, it does nothing
        }

        // MARK: - Message String Formatting
        override func prepareMessageString(
            baseMessage: BaseMessage,
            regexString: String,
            alignment: MessageBubbleAlignment = .left,
            formattingType: FormattingType
        ) -> NSAttributedString {
            let attrString = NSMutableAttributedString(string: "SURE")
            if alignment == .left {
                // Received message styling
                attrString.addAttribute(.foregroundColor, value: UIColor.blue, range: NSRange(location: 0, length: attrString.length))
            } else {
                // Sent message styling
                attrString.addAttribute(.foregroundColor, value: UIColor.green, range: NSRange(location: 0, length: attrString.length))
            }
            attrString.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: 18), range: NSRange(location: 0, length: attrString.length))
            return attrString
        }

        // MARK: - Text Tap Handler
        override func onTextTapped(baseMessage: BaseMessage, tappedText: String, controller: UIViewController?) {
            // Your Action
        }
    }
    ```
  </Tab>
</Tabs>

***

#### SetTemplate and AddTemplate

[CometChatMessageTemplate](/ui-kit/ios/message-template) is a pre-defined structure for creating message views that can be used as a starting point or blueprint for creating message views often known as message bubbles. For more information, you can refer to [CometChatMessageTemplate](/ui-kit/ios/message-template).

***

## Common Patterns

### Open Thread from Message List

Present the threaded messages view when a user taps on a message's reply count:

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    // In your message list delegate or action handler
    func openThread(for parentMessage: BaseMessage) {
        // Create a view controller to host the threaded messages
        let threadVC = UIViewController()
        threadVC.view.backgroundColor = .systemBackground
        
        // Create threaded message header
        let threadedHeader = CometChatThreadedMessageHeader()
        threadedHeader.set(parentMessage: parentMessage)
        threadedHeader.set(controller: threadVC)
        threadedHeader.translatesAutoresizingMaskIntoConstraints = false
        
        // Create message list for thread replies
        let messageList = CometChatMessageList()
        if let user = parentMessage.sender {
            messageList.set(user: user)
        }
        messageList.set(parentMessage: parentMessage)
        messageList.set(controller: threadVC)
        messageList.translatesAutoresizingMaskIntoConstraints = false
        
        // Create composer for thread replies
        let composer = CometChatMessageComposer()
        if let user = parentMessage.sender {
            composer.set(user: user)
        }
        composer.set(parentMessage: parentMessage)
        composer.set(controller: threadVC)
        composer.translatesAutoresizingMaskIntoConstraints = false
        
        // Add to view
        threadVC.view.addSubview(threadedHeader)
        threadVC.view.addSubview(messageList)
        threadVC.view.addSubview(composer)
        
        // Layout constraints
        NSLayoutConstraint.activate([
            threadedHeader.topAnchor.constraint(equalTo: threadVC.view.safeAreaLayoutGuide.topAnchor),
            threadedHeader.leadingAnchor.constraint(equalTo: threadVC.view.leadingAnchor),
            threadedHeader.trailingAnchor.constraint(equalTo: threadVC.view.trailingAnchor),
            
            messageList.topAnchor.constraint(equalTo: threadedHeader.bottomAnchor),
            messageList.leadingAnchor.constraint(equalTo: threadVC.view.leadingAnchor),
            messageList.trailingAnchor.constraint(equalTo: threadVC.view.trailingAnchor),
            messageList.bottomAnchor.constraint(equalTo: composer.topAnchor),
            
            composer.leadingAnchor.constraint(equalTo: threadVC.view.leadingAnchor),
            composer.trailingAnchor.constraint(equalTo: threadVC.view.trailingAnchor),
            composer.bottomAnchor.constraint(equalTo: threadVC.view.safeAreaLayoutGuide.bottomAnchor)
        ])
        
        self.navigationController?.pushViewController(threadVC, animated: true)
    }
    ```
  </Tab>
</Tabs>

### Customize Thread Header with Parent Message Info

Display additional context about the parent message in the thread header:

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    let threadedHeader = CometChatThreadedMessageHeader()
    threadedHeader.set(parentMessage: parentMessage)

    // Custom date formatting
    threadedHeader.set(datePattern: { timestamp in
        guard let timestamp = timestamp else { return "" }
        let date = Date(timeIntervalSince1970: TimeInterval(timestamp / 1000))
        let formatter = DateFormatter()
        formatter.dateFormat = "MMM d 'at' h:mm a"
        return formatter.string(from: date)
    })
    ```
  </Tab>
</Tabs>

### Filter Thread Replies

Show only specific types of messages in the thread:

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    // Filter to show only text messages in thread
    let messageRequestBuilder = MessagesRequest.MessageRequestBuilder()
        .set(parentMessageId: parentMessage.id)
        .set(types: ["text"])
        .set(limit: 30)

    let messageList = CometChatMessageList()
    messageList.set(messagesRequestBuilder: messageRequestBuilder)
    ```
  </Tab>
</Tabs>

***

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

  ```swift lines theme={null}
  let threadedMessageHeader = CometChatThreadedMessageHeader()
  threadedMessageHeader.set(controller: UIViewController) // Passing the controller is required
  ```
</Note>
