Skip to content

Tutorial_Add_Custom_Cell

Anton Schukin edited this page Dec 17, 2017 · 4 revisions

Tutorial: how to add a new cell to Chatto

You may want to create a cell from scratch to implement things like banners, time separators or your custom text cells.

Note that this is based just in Chatto framework, so from now on we're ignoring that ChattoAdditions even exits.

Let's say we want to create a time separator that appears before the first message sent on each day. The UI will be really simple: just a simple text centered with the date of the day.

What's needed:

  • TimeSeparatorCollectionViewCell: Subclass of UICollectionViewCell with our UI
  • TimeSeparatorModel: A ChatItemProtocol holding the data needed to configure the TimeSeparatorCollectionViewCell.
  • TimeSeparatorPresenter: Will be responsible for configuring the TimeSeparatorCollectionViewCell with the TimeSeparatorModel. Besides, it will have to register the cell in the UICollectionView and provide the height needed to render the cell. Learn more about the responsabilities of Presenters
  • TimeSeparatorPresenterBuilder: Will be responsible for creating a TimeSeparatorPresenter given a TimeSeparatorModel. It will be used during the Update-flow

Gluing all together

  • We need to tell Chatto that there's a time separator. We can do this in two ways:

    • Data-source approach, by just returning the TimeSeparatorModels within its chatItems property.
    • Decorator approach, by inserting the TimeSeparatorModels during the decoration phase of the Update-flow
  • We also need to tell Chatto about TimeSeparatorPresenterBuilder so it can create the presenters for each TimeSeparatorModel. In your BaseChatViewController subclass, just make sure that createPresenterBuilders includes TimeSeparatorPresenterBuilder.

override func createPresenterBuilders() -> [ChatItemType: [ChatItemPresenterBuilderProtocol]] {
    return [
        /* Other types */
        TimeSeparatorModel.chatItemType: [TimeSeparatorPresenterBuilder()]
    ]
}

That's it!! As you can see, it's really easy to add new types of cells in a systematic and clean way!