因为每个JSQMessage
对象都有一个date
属性,所以您可以简单地将每条消息的日期与前一条消息的日期进行比较。
[thisMessageDate timeIntervalSinceDate:(NSDate *)previousMessageDate]
将在几秒钟内为您提供差异。如果差异大于例如一分钟(或您想要的任何时间间隔),则显示时间戳。
这就是我的做法:
- (NSAttributedString *)collectionView:(JSQMessagesCollectionView *)collectionView attributedTextForCellTopLabelAtIndexPath:(NSIndexPath *)indexPath {
JSQMessage *message = [self.messages objectAtIndex:indexPath.item];
if (indexPath.item == 0) {
return [[JSQMessagesTimestampFormatter sharedFormatter] attributedTimestampForDate:message.date];
}
if (indexPath.item - 1 > 0) {
JSQMessage *previousMessage = [self.messages objectAtIndex:indexPath.item - 1];
if ([message.date timeIntervalSinceDate:previousMessage.date] / 60 > 1) {
return [[JSQMessagesTimestampFormatter sharedFormatter] attributedTimestampForDate:message.date];
}
}
return nil;
}
然后重复此逻辑以确保时间戳具有正确的高度:
- (CGFloat)collectionView:(JSQMessagesCollectionView *)collectionView
layout:(JSQMessagesCollectionViewFlowLayout *)collectionViewLayout heightForCellTopLabelAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.item == 0) {
return kJSQMessagesCollectionViewCellLabelHeightDefault;
}
if (indexPath.item - 1 > 0) {
JSQMessage *previousMessage = [self.messages objectAtIndex:indexPath.item - 1];
JSQMessage *message = [self.messages objectAtIndex:indexPath.item];
if ([message.date timeIntervalSinceDate:previousMessage.date] / 60 > 1) {
return kJSQMessagesCollectionViewCellLabelHeightDefault;
}
}
return 0.0f;
}