我试图创建一个带有图标的自定义消息单元格(右侧为传入,左侧为传出)
我已经将JSQMessagesCollectionViewCellOutgoing
子类化,并在我想要的位置显示图标。大。我无法做到的是将文本视图的宽度设置得更小以考虑图标。我认为这是我的自定义传出xib文件中的一个简单的自动布局更改,但是当应用程序运行时,自动布局宽度被覆盖。
如何从textViewMarginHorizontalSpaceConstraint
或JSQMessagesCollectionViewCell
JSQMessagesCollectionViewCell
更新(直接或间接)JSQMessagesCollectionViewCellOutgoing
答案 0 :(得分:1)
您不必创建JSQMessagesCollectionViewCell的任何扩展名,
除非您想要更改Cell的结构,否则请更改发件人/收件人头像的位置或上/下标签位置。
我是JSQMessage的新手,但这是我的解决方案:
如果你只想要一个自定义视图的消息的主要内容部分,这是泡沫圆角部分:),那么
您只需要一个自定义的JSQMediaItem类,
并覆盖
- (UIView *)mediaView
方法,然后您可以完全控制内容视图。
技巧部分是,您必须在
之前获得内容视图的高度- (CGSize)mediaViewDisplaySize
这个方法由JSQ框架调用。 因此,最好的方法是在自定义类的init方法中动态计算返回视图的高度:
- (instancetype)initWithImage:(UIImage *)image title:(NSString*)title message:(NSString*)msg
这是我的自定义类,需要显示事件消息,标题,图像和消息。顺便说一句,只有消息部分高度是动态的,所以我只是使用
计算了这个部分[NSString boundingRectWithSize:]
EventMediaItem.h
#import <JSQMessagesViewController/JSQMediaItem.h>
NS_ASSUME_NONNULL_BEGIN
/**
* The `EventMediaItem` class is a concrete `JSQMediaItem` subclass that implements the `JSQMessageMediaData` protocol
* and represents a event media message. An initialized `EvnetMediaItem` object can be passed
* to a `JSQMediaMessage` object during its initialization to construct a valid media message object.
* You may wish to subclass `EventMediaItem` to provide additional functionality or behavior.
*/
@interface EventMediaItem : JSQMediaItem <JSQMessageMediaData, NSCoding, NSCopying>
/**
* The image for the event media item. The default value is `nil`.
*/
@property (copy, nonatomic, nullable) UIImage *image;
/**
* The title for the event media item. The default value is `nil`.
*/
@property (copy, nonatomic, nullable) NSString *title;
/**
* The message for the event media item. The default value is `nil`.
*/
@property (copy, nonatomic, nullable) NSString *message;
/**
* Initializes and returns a event media item object having the given image.
*
* @param image The image for the event media item. This value may be `nil`.
* @param title The title for the event media item. This value may be `nil`.
* @param message The message for the event media item. This value may be `nil`.
*
* @return An initialized `EventMediaItem`.
*
* @discussion If the image must be dowloaded from the network,
* you may initialize a `EventMediaItem` object with a `nil` image.
* Once the image has been retrieved, you can then set the image property.
*/
- (instancetype)initWithImage:(UIImage *)image title:(NSString*)title message:(NSString*)msg;
@end
NS_ASSUME_NONNULL_END
和EventMediaItem.m
#import "EventMediaItem.h"
#import "JSQMessagesMediaPlaceholderView.h"
#import "JSQMessagesMediaViewBubbleImageMasker.h"
#import "UIImage+JSQMessages.h"
#import "JSQMessagesBubbleImageFactory.h"
#import <MobileCoreServices/UTCoreTypes.h>
#define paddingStart 15.0f
#define indent 10.0f
#define spacing 7.0f
#define paddingTop 3.0f
#define heightTitle 40.0f
#define heightImage 100.0f
#define magicDelta 20.0f
@interface EventMediaItem (){
CGFloat heightMsgView;
NSDictionary *attrsDictionary;
}
@property (strong, nonatomic) UIView *rootView;
@property (strong, nonatomic) UIImageView *cachedImageView;
@property (strong, nonatomic) UILabel *titleView;
@property (strong, nonatomic) UITextView *messageView;
@end
@implementation EventMediaItem
#pragma mark - Initialization
- (instancetype)initWithImage:(UIImage *)image title:(NSString*)title message:(NSString*)msg
{
self = [super init];
if (self) {
_image = [image copy];
_cachedImageView = nil;
_message = [msg copy];
_messageView = nil;
_title = [title copy];
_titleView = nil;
CGSize size;
size = CGSizeMake(210.0, 500);
if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
size = CGSizeMake(315.0, 500);
}
UITextView *tmp = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height-(paddingTop+heightImage+heightTitle))];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.headIndent = indent;
paragraphStyle.firstLineHeadIndent = indent;
paragraphStyle.lineSpacing = spacing;
UIFont *font = [UIFont fontWithName:@"HelveticaNeue" size:14.f];
// save the attrs for future use
attrsDictionary =
@{ NSParagraphStyleAttributeName: paragraphStyle, NSFontAttributeName:font}; // <-- there are many more attrs, e.g NSFontAttributeName
tmp.attributedText = [[NSAttributedString alloc] initWithString:_message attributes:attrsDictionary];
// *** ADJUST VIEW SIZE ***
CGRect containSize = [tmp.text boundingRectWithSize:CGSizeMake(size.width, 400) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrsDictionary context:nil];
heightMsgView = containSize.size.height;
// *** ADJUST VIEW SIZE ***
}
return self;
}
- (void)clearCachedMediaViews
{
[super clearCachedMediaViews];
_cachedImageView = nil;
}
#pragma mark - Setters
- (void)setImage:(UIImage *)image
{
_image = [image copy];
_cachedImageView = nil;
}
- (void)setAppliesMediaViewMaskAsOutgoing:(BOOL)appliesMediaViewMaskAsOutgoing
{
[super setAppliesMediaViewMaskAsOutgoing:appliesMediaViewMaskAsOutgoing];
_cachedImageView = nil;
}
#pragma mark - JSQMessageMediaData protocol
- (UIView *)mediaView
{
UIColor *bgc = [UIColor colorWithRed:243/255.0 green:243/255.0 blue:243/255.0 alpha:1];
if (self.image == nil) {
return nil;
}
if (self.cachedImageView == nil) {
CGSize size = CGSizeMake(210.0, 400);
self.rootView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, size.width, paddingTop+heightTitle+heightImage+heightMsgView+magicDelta)];
self.rootView.backgroundColor = bgc;
self.titleView = [[UILabel alloc] initWithFrame:CGRectMake(paddingStart, paddingTop, size.width-15, heightTitle)];
self.titleView.font = [UIFont systemFontOfSize:16 weight:20];
self.titleView.textColor = [UIColor darkGrayColor];
self.titleView.numberOfLines = 2;
self.titleView.text = _title;
UIImageView *imageView = [[UIImageView alloc] initWithImage:self.image];
imageView.frame = CGRectMake(0.0f, self.titleView.frame.size.height, size.width, heightImage);
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.clipsToBounds = YES;
self.cachedImageView = imageView;
self.messageView = [[UITextView alloc] initWithFrame:CGRectMake(00.0f, self.titleView.frame.size.height+self.cachedImageView.frame.size.height, size.width, heightMsgView+magicDelta)];
self.messageView.textColor = [UIColor darkGrayColor];
self.messageView.font = [UIFont systemFontOfSize:15];
self.messageView.backgroundColor = bgc;
self.messageView.editable = NO;
//---
NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString:_message attributes:attrsDictionary];
NSRange range = [self.message rangeOfString:NSLocalizedStringFromTable(@"EventListMore", @"Message", @"")];
[attrString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:108/255.0 green:210/255.0 blue:240/255.0 alpha:1] range:range]; //6cd2f0
//---
self.messageView.attributedText = attrString;
//add the views to mediaView
[self.rootView addSubview:self.cachedImageView];
[self.rootView addSubview:self.messageView];
[self.rootView addSubview:self.titleView];
//apply bubble factory
JSQMessagesBubbleImageFactory *factory = [[JSQMessagesBubbleImageFactory alloc] initWithBubbleImage:[UIImage jsq_bubbleRegularTaillessImage] capInsets:UIEdgeInsetsZero];
JSQMessagesMediaViewBubbleImageMasker*masker = [[JSQMessagesMediaViewBubbleImageMasker alloc] initWithBubbleImageFactory:factory];
[masker applyIncomingBubbleImageMaskToMediaView:self.rootView];
}
return self.rootView;
}
- (CGSize)mediaViewDisplaySize
{
if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
return CGSizeMake(315.0f, paddingTop+heightTitle+heightImage+heightMsgView);
}
return CGSizeMake(210.0f, paddingTop+heightTitle+heightImage+heightMsgView+magicDelta);
}
- (NSUInteger)mediaHash
{
return self.hash;
}
- (NSString *)mediaDataType
{
return (NSString *)kUTTypeMessage;
}
- (id)mediaData
{
return UIImageJPEGRepresentation(self.image, 1);
}
#pragma mark - NSObject
- (NSUInteger)hash
{
return super.hash ^ self.image.hash;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"<%@: image=%@, appliesMediaViewMaskAsOutgoing=%@>",
[self class], self.image, @(self.appliesMediaViewMaskAsOutgoing)];
}
#pragma mark - NSCoding
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
_image = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(image))];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[super encodeWithCoder:aCoder];
[aCoder encodeObject:self.image forKey:NSStringFromSelector(@selector(image))];
}
#pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone
{
EventMediaItem *copy = [[EventMediaItem allocWithZone:zone] initWithImage:self.image title:self.title message:self.message];
copy.appliesMediaViewMaskAsOutgoing = self.appliesMediaViewMaskAsOutgoing;
return copy;
}
@end
如何使用 首先,注册单元格笔尖(Swift项目)
self.collectionView.registerNib(UINib(nibName: "VobMessagesMediaCellIncoming", bundle: nil), forCellWithReuseIdentifier: "VobMessagesMediaCellIncoming")
VobMessagesMediaCellIncoming只是您正在使用的任何崩溃消息单元的副本,因为我的经验是您必须使用不同的标识符复制新的,而不是使用相同的nib来处理正常的消息和媒体消息,否则JSQMessageCollectionView可能会混淆重用单元格时显示异常消息。
然后,在cellForItemAtIndexPath中,您将逻辑分叉为 NOT 设置单元格的textView,因为相应的消息是Media-type(EventMediaItem),并且单元格的textView的任何设置都将导致断言失败:
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! JSQMessagesCollectionViewCell
let message = viewModel.messageBubbleModelView(indexPath.item)
if !message.isMediaMessage {
let color = senderId == message.senderId ? UIColor.whiteColor() : AppColor.BodyTextColor
cell.textView.textColor = color
cell.textView.linkTextAttributes = [
NSForegroundColorAttributeName: color,
NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue
]
}
//set position nickname
cell.messageBubbleTopLabel.textAlignment = .Left
let edgeInset = cell.messageBubbleTopLabel.textInsets
cell.messageBubbleTopLabel.textInsets = UIEdgeInsetsMake(edgeInset.top, edgeInset.left - 20, edgeInset.bottom, edgeInset.right + 20)
...
}
顺便说一下,isMediaMessage属性来自JSQMessage,如果你初始化一个JSQMessage并且它将被设置为ture; 最后,在您的自定义JSQMessage中: (MessagePost是我自己项目的消息模型)
class MessageBubbleViewModel: JSQMessage {
let messagePost: MessagePost
init(messagePost: MessagePost) {
self.messagePost = messagePost
if messagePost.isEvent {
let eventMedia:EventMediaItem = EventMediaItem(image: UIImage(named: "some cool image")!, title: messagePost.title, message: messagePost.msg)
super.init(senderId: String(messagePost.senderId),
senderDisplayName: messagePost.senderNickName,
date: messagePost.updatedAt,
media: eventMedia)
}else{
super.init(
senderId: String(messagePost.senderId),
senderDisplayName: messagePost.senderNickName,
date: messagePost.updatedAt,
text: messagePost.text)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
似乎有很多其他方法可以实现这一点,你可以参考这个链接: https://github.com/jessesquires/JSQMessagesViewController/issues?utf8=%E2%9C%93&q=+%5Bcustom+cells%5D+in%3Atitle 但是,我无法从这些线程中获取任何有用的信息。 - #
答案 1 :(得分:0)
我建议做这样的事情
extension JSQMessagesCollectionViewCellOutgoing {
public func messageContentSmaller() {
self.messageBubbleContainerView?.setContentCompressionResistancePriority(UILayoutPriorityDefaultLow, forAxis: .Horizontal)
}
}
您可能还需要
self.messageBubbleContainerView.setNeedsLayout
如果有帮助,请告诉我。