在聊天室中显示系统消息

时间:2019-06-07 06:56:09

标签: swift xcode chat messagekit

我正在努力如何在聊天室中显示系统消息。目前,我已经在Swift中使用MessageKit构建了聊天室,并完成了整个UI。我想要的是,当我单击右上角的红色按钮时,系统消息“已轻按该按钮”将自动显示在聊天室中,如下面的示例图片所示。非常感谢任何人的帮助!

sample picture

1 个答案:

答案 0 :(得分:0)

这个答案可能有点晚了,但是解决方法很简单。您需要做的就是创建一个自定义单元,并使用消息视图控制器数据源对其进行配置。

有一个comprehensive guide,您可以在官方回购中关注,以寻求有关example的帮助

这里有一些演示代码(由于我引用了一些自定义UIView子类,因此您将无法复制和粘贴此代码)

首先,创建您的UICollectionViewCell

class SystemMessageCell: CollectionCell<MessageType> {
  lazy var messageText = Label()
    .variant(.regular(.small))
    .color(.gray)
    .align(.center)

  override func setupView() {
    addSubview(messageText)
  }

  override func setupConstraints() {
    messageText.snp.makeConstraints { $0.edges.equalToSuperview() }
  }

  override func update() {
    guard let item = item else { return }
    switch item.kind {
    case .custom(let kind):
      guard let kind = kind as? ChatMessageViewModel.Kind else { return }
      switch kind {
      case .system(let systemMessage):
        messageText.text = systemMessage
      }
    default:
      break
    }
  }
}

第二,您需要创建两个单独的文件。 一个是尺寸计算器,另一个是自定义流程布局。

class SystemMessageSizeCalculator: MessageSizeCalculator {
  override func messageContainerSize(for message: MessageType) -> CGSize {
    // Just return a fixed height.
    return CGSize(width: UIScreen.main.bounds.width, height: 20)
  }
}
class SystemMessageFlowLayout: MessagesCollectionViewFlowLayout {
  lazy open var sizeCalculator = SystemMessageSizeCalculator(layout: self)

  override open func cellSizeCalculatorForItem(at indexPath: IndexPath) -> CellSizeCalculator {
    let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
    if case .custom = message.kind {
      return sizeCalculator
    }
    return super.cellSizeCalculatorForItem(at: indexPath);
  }
}

最后,将其全部挂接到MessagesViewController中,如下所示:

class ChatViewController: MessagesViewController {

  override func viewDidLoad() {
    messagesCollectionView = MessagesCollectionView(frame: .zero, collectionViewLayout: SystemMessageFlowLayout())
    super.viewDidLoad()
    messagesCollectionView.register(SystemMessageCell.self)
  }

  // MARK: - Custom Cell

  override open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
      fatalError("Ouch. nil data source for messages")
    }

    let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
    if case .custom = message.kind {
      let cell = messagesCollectionView.dequeueReusableCell(SystemMessageCell.self, for: indexPath)
      cell.item = message
      return cell
    }
    return super.collectionView(collectionView, cellForItemAt: indexPath)
  }
}

最终结果将是这样:

Sample screenshot