【问题标题】:How to left/right-align custom UITableView cell如何左/右对齐自定义 UITableView 单元格
【发布时间】:2020-05-14 08:17:36
【问题描述】:

我正在编写一个“聊天机器人”应用程序,为了保存消息气泡,我有一个 UITableView 和一个自定义消息气泡形状的单元格。这是到目前为止的样子:

所有单元格看起来都一样,除了我希望每个其他单元格都为表格宽度的一半,并交替右/左对齐。我怎么能以编程方式做到这一点?

【问题讨论】:

  • 我在 tableView 中实现了聊天。您的自定义表格视图类是什么样的?对于发送或接收的消息单元,您将需要单独的类。
  • 这能回答你的问题吗? create a simple chat view in ios

标签: ios swift uikit


【解决方案1】:

更好的方法——创建两个类InMessageCell、OutMessageCell,并将所有属性(比如所有元素的对齐)隐藏在这个单元格内。两个单元格将具有相同的宽度,但所有气泡将在一侧或另一侧移动。它可能继承自主类 MessageCell,因此所有逻辑都可能保留在主类中,但 UI 部分 - 被拆分了。

【讨论】:

    【解决方案2】:

    使用custom table view cells 实现此目的的两种直接方法:

    1. 有两个不同的细胞类别。它们可以共享大部分实现(例如,通过类继承),但布局不同(一个左对齐,一个右对齐)。对于表格中的每一行,确定您需要使用哪个单元格,然后将相应的单元格出列。
    2. 有一个单元类,其布局可以在出队时切换。 (此切换的具体外观当然取决于您选择如何布局单元格。例如,您可以将常量交换为您通过@IBOutlet 引用的自动布局约束、切换背景图像或更改对齐属性堆栈视图等。)

    这两种方式都取决于决定在 UITableViewDataSource 的 tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) 函数中使用哪种单元格风格。

    这是一个使用第一种方法的稍微抽象的示例。在你的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
        }
    

    【讨论】:

      【解决方案3】:

      您可以给表格视图单元格一个值来了解它。然后您可以使用自动布局(SnapKit)使其左对齐或右对齐

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-27
        • 2015-06-16
        • 2015-01-03
        相关资源
        最近更新 更多