Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
MessageKitの動作確認用
import UIKit
import MessageKit
class ViewController: MessagesViewController {
var messageList: [MockMessage] = []
let dateFormatter:DateFormatter = DateFormatter() //日時のフォーマットを管理するもの
lazy var formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
return formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
print("App open")
DispatchQueue.main.async {
// messageListにメッセージの配列をいれて
self.messageList = self.getMessages()
// messagesCollectionViewをリロードして
self.messagesCollectionView.reloadData()
// 一番下までスクロールする
self.messagesCollectionView.scrollToBottom()
}
messagesCollectionView.messagesDataSource = self
messagesCollectionView.messagesLayoutDelegate = self
messagesCollectionView.messagesDisplayDelegate = self
messagesCollectionView.messageCellDelegate = self
messageInputBar.delegate = self
messageInputBar.sendButton.tintColor = UIColor.lightGray
// メッセージ入力時に一番下までスクロール
scrollsToBottomOnKeyboardBeginsEditing = true // default false
maintainPositionOnKeyboardFrameChanged = true // default false
//DateFormatter()で日付と時刻と地域を指定(今回は日本時間を指定)
dateFormatter.dateStyle = .medium //日付の表示スタイルを決定
dateFormatter.timeStyle = .short //時刻の表示スタイルを決定
dateFormatter.locale = Locale(identifier: "ja_JP")//地域を決定
}
// サンプル用に適当なメッセージ
func getMessages() -> [MockMessage] {
return [
createMessage(text: "String")
]
}
func createMessage(text: String) -> MockMessage {
let attributedText = NSAttributedString(string: text, attributes: [.font: UIFont.systemFont(ofSize: 15),
.foregroundColor: UIColor.black])
return MockMessage(attributedText: attributedText, sender: otherSender(), messageId: UUID().uuidString, date: Date())
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension ViewController: MessagesDataSource {
func currentSender() -> SenderType {
return Sender(id: "123", displayName: "自分")
}
func otherSender() -> Sender {
return Sender(id: "456", displayName: "知らない人")
}
func numberOfSections(in messagesCollectionView: MessagesCollectionView) -> Int {
return messageList.count
}
func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType {
return messageList[indexPath.section]
}
// メッセージの上に文字を表示
func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
if indexPath.section % 3 == 0 {
return NSAttributedString(
string: MessageKitDateFormatter.shared.string(from: message.sentDate),
attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 10),
NSAttributedString.Key.foregroundColor: UIColor.darkGray]
)
}
return nil
}
// メッセージの上に文字を表示(名前)
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)])
}
}
// メッセージのdelegate
extension ViewController: MessagesDisplayDelegate {
// メッセージの色を変更(デフォルトは自分:白、相手:黒)
func textColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor {
return isFromCurrentSender(message: message) ? .white : .darkText
}
// メッセージの背景色を変更している(デフォルトは自分:緑、相手:グレー)
func backgroundColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor {
return isFromCurrentSender(message: message) ?
UIColor(red: 69/255, green: 193/255, blue: 89/255, alpha: 1) :
UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1)
}
// メッセージの枠にしっぽを付ける
func messageStyle(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageStyle {
let corner: MessageStyle.TailCorner = isFromCurrentSender(message: message) ? .bottomRight : .bottomLeft
return .bubbleTail(corner, .curved)
}
// アイコンをセット
func configureAvatarView(_ avatarView: AvatarView, for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) {
// message.sender.displayNameとかで送信者の名前を取得できるので
// そこからイニシャルを生成するとよい
let avatar = Avatar(initials: "")
avatarView.set(avatar: avatar)
}
}
// 各ラベルの高さを設定(デフォルト0なので必須)
extension ViewController: MessagesLayoutDelegate {
func cellTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
if indexPath.section % 3 == 0 { return 10 }
return 0
}
func messageTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
return 16
}
func messageBottomLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
return 16
}
}
extension ViewController: MessageCellDelegate {
// メッセージをタップした時の挙動
func didTapMessage(in cell: MessageCollectionViewCell) {
print("Message tapped")
}
}
extension ViewController: MessageInputBarDelegate {
// メッセージ送信ボタンをタップした時の挙動
func inputBar(_ inputBar: MessageInputBar, didPressSendButtonWith text: String) {
for _ in inputBar.inputTextView.components {
let attributedText = NSAttributedString(string: text, attributes: [.font: UIFont.systemFont(ofSize: 15),
.foregroundColor: UIColor.white])
let message = MockMessage(attributedText: attributedText, sender: currentSender(), messageId: UUID().uuidString, date: Date())
messageList.append(message)
messagesCollectionView.insertSections([messageList.count - 1])
}
//inputBarの中のテキストを表示して
inputBar.inputTextView.text = ""
//一番下までスクロールしている
messagesCollectionView.scrollToBottom()
print("messageList when sendButton pressed:\(messageList)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.