user13501445
user13501445

Reputation:

How to left/right-align custom UITableView cell

I’m coding a “chatbot” app, and to hold the message bubbles I have a UITableView and a custom message-bubble shaped cell. Here’s what it looks like so far: enter image description here

All the cells will look the same, except I’d like every other cell to be, say, half the width of the table and alternating right/left aligned. How could I do this programmatically?

Upvotes: 0

Views: 1091

Answers (3)

Gamma
Gamma

Reputation: 1367

Two straightforward ways of achieving this by using custom table view cells:

  1. Have two different cell classes. They can share much of their implementation (e.g. by class heritage), but differ in their layout (one is left aligned, one right aligned). For each row in your table, decide which cell you need to use, and dequeue the appropriate one.
  2. Have one cell class whose layout can be toggled when it's being dequeued. (How exactly this toggle looks like depends of course on how you chose to layout your cell. It could e.g. be that you exchange the constant to an autolayout constraint you reference via @IBOutlet, the switching of a background image, or changing the alignment property of a stack view, among many others.)

Both ways depend on making a decision which cell flavor to use in your UITableViewDataSource's tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) function.

Here is a slightly abstract example using the first method. In your UITableViewDataSource:

enum ChatCellAlignment {
    case left
    case right
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cellAlignment: ChatCellAlignment = self.cellAlignmentForIndexPath(indexPath) // you need to implement something like this
        var identifier = "Default"

        switch cellAlignment {
            case .left:
                identifier = "LeftAlignedBubbleCell"
            case .right:
                identifier = "RightAlignedBubbleCell"
        }

        let cell = self.tableView.dequeueReusableCell(withIdentifier: identifier)

        if let cell = cell as? ChatBubbleCell { // assuming your custom cell classes all inherit from a "ChatBubbleCell"
            cell.set(text: self.textForIndexPath(indexPath))
            ... // whatever setup you need to do on your custom cell
        }

        return cell
    }

Upvotes: 1

The better way - to create two classes InMessageCell, OutMessageCell, and add all properties (like aligning of all elements) hide inside of this cell. Both cell will have the same width, but all bubbles will be moved on one or other side. It may inheritance from the main class MessageCell, so all logic may stay in main class, but UI part - splitted up.

Upvotes: 1

King.lbt
King.lbt

Reputation: 881

You can give the table view cell a value to know it. Then you can use autolayout (SnapKit) to make it align left or right

Upvotes: 0

Related Questions