swift - 在消息包聊天中显示用户名?

标签 swift messagekit

我正在努力寻找一种在 MessageKit 聊天 View Controller 中显示用户名的方法。我从示例项目中复制了 MessagesDataSource,但没有成功。这是我的 MessagesDataSource 当前的样子:

extension ChatViewController: MessagesDataSource {

    func currentSender() -> Sender {
        //guard let currentUserID = User.current?.key else {return nil}
        let newSender = Sender(id: (User.current?.key)!, displayName: (User.current?.username)!)
        return newSender
    }

    func numberOfSections(in messagesCollectionView: MessagesCollectionView) -> Int {
        //return 1
        return messages.count
    }

    func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType {

        return messages[indexPath.section]
    }

    func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {

        return NSAttributedString(string: MessageKitDateFormatter.shared.string(from: message.sentDate), attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 10), NSAttributedString.Key.foregroundColor: UIColor.darkGray])
    }

    func messageTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
        let name = message.sender.displayName
        return NSAttributedString(string: name, attributes: [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .caption1)])
    }

    func messageBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {

        let dateString = formatter.string(from: message.sentDate)
        return NSAttributedString(string: dateString, attributes: [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .caption2)])
    }
}

如果我在 let name = message.sender.displayName 之后放置一个断点,正确的用户名将显示在控制台输出中。但是,它仍然没有出现在聊天记录中。聊天 View 仍然只显示头像和消息,没有其他内容。

我错过了什么?

谢谢

最佳答案

虽然我不知道你使用的 MessageKit 版本是什么,但我很确定如果你尝试过这个一切都应该工作得很好,

func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
    let name = message.sender.displayName
    return NSAttributedString(
      string: name,
      attributes: [
        .font: UIFont.preferredFont(forTextStyle: .caption1),
        .foregroundColor: UIColor(white: 0.3, alpha: 1)
      ]
    )
  }

因为我没有看到任何名为 messageTopLabelAttributedTextdataSource 函数

关于swift - 在消息包聊天中显示用户名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54961955/

相关文章:

ios - Firebase 循环多级节点

swift - URLSession.shared.dataTaskPublisher 在 IOS 13.3 上不起作用

ios - 在 UserDefaults 中保存并添加整数值并在添加值后检索

ios - 当用户使用 'MessageKit' 库点击发送时,监听器不会触发

ios - 使用 Firebase 查询重新加载数据后复制 collectionView 单元格

ios - MessageKit - 如何在 MessagesViewController 的子类中异步加载图像?

ios - 在封闭的 TextView 中使用动态字体自动调整 View 大小

ios - 消息线程的左对齐 `MessageKit` swift

ios - 崩溃 : com. apple.root.default-qos SIGABRT ABORT