Элегантный контроллер просмотра чата готового к ходу для приложений для чата iOS , в котором используется Quickblox communication backend .
#Функции
Quickblox .
pod 'QMChatViewController'
Перетащите папку QMChatViewController в папку проекта и ссылка на соответствующую цель.
Установить зависимости.
Пример включен в репозиторий. Попробуйте, чтобы увидеть, как работает контроллер просмотра чата.
Шаги, чтобы добавить QMChatViewController в ваше приложение:
Создайте подкласс QMChatViewController . Вы можете создать его как из кода, так и из интерфейса.
Откройте подкласс QMChatViewController и сделайте следующее в методе ViewDidload :
self.senderID = 2000 ;
self.senderDisplayName = @" user1 " ;[ self .chatDataSource addMessages: <array of messages>];Обрабатывать сообщение отправки.
- ( void )didPressSendButton:(UIButton *)button
withMessageText:( NSString *)text
senderId:( NSUInteger )senderId
senderDisplayName:( NSString *)senderDisplayName
date:( NSDate *)date {
// Add sending message - for example:
QBChatMessage *message = [QBChatMessage message ];
message. text = text;
message. senderID = senderId;
QBChatAttachment *attacment = [[QBChatAttachment alloc ] init ];
message. attachments = @[attacment];
[ self .chatDataSource addMessage: message];
[ self finishSendingMessageAnimated: YES ];
// Save message to your cache/memory storage.
// Send message using Quickblox SDK
}Возврат классы Cell Просмотр классов, специфичные для сообщения чата:
- ( Class )viewClassForItem:(QBChatMessage *)item {
// Cell class for message
if (item. senderID != self. senderID ) {
return [QMChatIncomingCell class ];
}
else {
return [QMChatOutgoingCell class ];
}
return nil ;
}
Рассчитайте размер ячейки и минимальную ширину:
- ( CGFloat )collectionView:(QMChatCollectionView *)collectionView minWidthAtIndexPath:( NSIndexPath *)indexPath {
QBChatMessage *item = [ self .chatDataSource messageForIndexPath: indexPath];
NSAttributedString *attributedString = item. senderID == self. senderID ?
[ self bottomLabelAttributedStringForItem: item] : [ self topLabelAttributedStringForItem: item];
CGSize size = [TTTAttributedLabel sizeThatFitsAttributedString: attributedString
withConstraints: CGSizeMake ( 1000 , 10000 )
limitedToNumberOfLines: 1 ];
return size. width ;
}Вверху, снизу и текстовые этикетки.
- ( NSAttributedString *)attributedStringForItem:(QBChatMessage *)messageItem {
UIColor *textColor = [messageItem senderID ] == self. senderID ?
[UIColor whiteColor ] : [UIColor colorWithWhite: 0.290 alpha: 1.000 ];
UIFont *font = [UIFont fontWithName: @" Helvetica " size: 15 ];
NSDictionary *attributes = @{ NSForegroundColorAttributeName :textColor,
NSFontAttributeName :font};
NSMutableAttributedString *attrStr =
[[ NSMutableAttributedString alloc ] initWithString: messageItem.text
attributes: attributes];
return attrStr;
}
- ( NSAttributedString *)topLabelAttributedStringForItem:(QBChatMessage *)messageItem {
if (messageItem. senderID == self. senderID ) {
return nil ;
}
UIFont *font = [UIFont fontWithName: @" Helvetica " size: 14 ];
UIColor *textColor = [UIColor colorWithRed: 0.184 green: 0.467 blue: 0.733 alpha: 1.000 ];
NSDictionary *attributes = @{ NSForegroundColorAttributeName :textColor,
NSFontAttributeName :font};
NSMutableAttributedString *attrStr =
[[ NSMutableAttributedString alloc ] initWithString: @" nickname "
attributes: attributes];
return attrStr;
}
- ( NSAttributedString *)bottomLabelAttributedStringForItem:(QBChatMessage *)messageItem {
UIFont *font = [UIFont fontWithName: @" Helvetica " size: 12 ];
UIColor *textColor = [messageItem senderID ] == self. senderID ?
[UIColor colorWithWhite: 1.000 alpha: 0.510 ] : [UIColor colorWithWhite: 0.000 alpha: 0.490 ];
NSDictionary *attributes = @{ NSForegroundColorAttributeName :textColor,
NSFontAttributeName :font};
NSString *dateStr = @" 10:20 " ;
NSMutableAttributedString *attrStr =
[[ NSMutableAttributedString alloc ] initWithString: dateStr
attributes: attributes];
return attrStr;
}Изменение атрибутов ячейки чата сбора без изменения ограничений:
struct QMChatLayoutModel {
CGSize avatarSize;
CGSize containerSize;
UIEdgeInsets containerInsets;
CGFloat topLabelHeight;
CGFloat bottomLabelHeight;
CGSize staticContainerSize;
CGFloat maxWidthMarginSpace;
};
typedef struct QMChatLayoutModel QMChatCellLayoutModel;Вы можете изменить эти атрибуты в этом методе:
- (QMChatCellLayoutModel)collectionView:(QMChatCollectionView *)collectionView layoutModelAtIndexPath:( NSIndexPath *)indexPath {
QMChatCellLayoutModel layoutModel = [ super collectionView: collectionView layoutModelAtIndexPath: indexPath];
// Update attributes here ...
return layoutModel;
}Поэтому, если вы хотите скрыть верхнюю метку или нижнюю метку, вам просто нужно установить их высоту на 0.
QMChatViewController поддерживает сообщения сочетных ячеек изображения. QMChatAttachmentIncomingCell используется для входящих вложений, QMChatAttachmentOutgoingCell используется для исходящих вложений. Оба они имеют метку прогресса для отображения прогресса загрузки. XIB также включены.
QMChatViewController содержит свой диспетчер источников данных под названием QMChatDataSource . Он имеет реализацию всех методов, которые вам необходимо работать с QMChatViewController . Этот класс должен использоваться для добавления, обновления и удаления сообщений из источника данных. QMChatDataSource имеет делегированное, которое называется всякий раз, когда источник данных был изменен.
Для получения дополнительной информации о методах и его использовании ознакомьтесь с нашим встроенным документом в QMChatDataSource.h .
Доступна встроенная кодовая документация.
Смотрите лицензию