よくあるLine風にするために
- MessagesCollectionViewのMessagesCollectionViewFlowLayoutで全体のレイアウトを指定できる
- アイコン位置調整
- TextMessageSizeCalculatorのmessageLabelFontでフォント指定
import UIKit
import MessageKit
import Rswift
class ChateViewController: MessagesViewController {
override func viewDidLoad() {
super.viewDidLoad()
# 略
// レイアウト指定
if let layout = self.messagesCollectionView.collectionViewLayout as? MessagesCollectionViewFlowLayout {
// 自分のアイコンを非表示
layout.setMessageOutgoingAvatarSize(.zero)
// 非表示の分、吹き出しを移動して空白を埋める
let insets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
layout.setMessageOutgoingMessageTopLabelAlignment(LabelAlignment(textAlignment: .right, textInsets: insets))
layout.setMessageOutgoingMessageBottomLabelAlignment(LabelAlignment(textAlignment: .right, textInsets: insets))
// メッセージのフォント
layout.textMessageSizeCalculator.messageLabelFont = R.font.notoSansCJKjpSubRegular(size: 12.0)!
}
}
テキスト内の詳細はMessagesDisplayDelegateで指定する
extension ChatMessageViewController: MessagesDisplayDelegate {
// URL青色、下線を表示
func detectorAttributes(for detector: DetectorType, and message: MessageType, at indexPath: IndexPath) -> [NSAttributedStringKey: Any] {
let detectorAttributes: [NSAttributedStringKey: Any] = {
[
NSAttributedStringKey.foregroundColor: UIColor.blue,
NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue,
NSAttributedStringKey.underlineColor: UIColor.blue,
NSAttributedStringKey.font: R.font.notoSansCJKjpSubRegular(size: 12.0)!
]
}()
MessageLabel.defaultAttributes = detectorAttributes
return MessageLabel.defaultAttributes
}
// メッセージのURLに属性を適用
func enabledDetectors(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> [DetectorType] {
return [.url]
}
}
DetectorTypeの種類はここを参照
https://github.com/MessageKit/MessageKit/blob/master/Sources/Models/DetectorType.swift