1

我正在尝试创建一个具有图标的自定义消息单元格(右侧用于传入,左侧用于传出)

我已经分类JSQMessagesCollectionViewCellOutgoing并在我想要的地方显示了图标。伟大的。我无法做的是让文本视图的宽度更小以考虑图标。我认为这是我的自定义传出 xib 文件中的一个简单的自动布局更改,但是当应用程序运行时,自动布局宽度被覆盖。

我如何从或者的子类中textViewMarginHorizontalSpaceConstraint更新(直接或间接)JSQMessagesCollectionViewCellJSQMessagesCollectionViewCellJSQMessagesCollectionViewCellOutgoing

4

2 回答 2

1

您不必创建 JSQMessagesCollectionViewCell 的任何扩展,

除非您想更改单元格的结构,否则请更改发送者/接收者头像的位置或上/下标签位置。

我对 JSQMessage 很陌生,但这是我的解决方案:

如果您只想要消息的主要内容部分的自定义视图,即气泡圆角部分:),那么

您只需要一个自定义的 JSQMediaItem 类

然后你覆盖

- (UIView *)mediaView

方法,然后您可以完全控制内容视图。

技巧部分是,您必须先获取内容视图的高度

- (CGSize)mediaViewDisplaySize

该方法由 JSQ 框架调用。所以最好的方法是在自定义类的 init 方法中动态计算返回视图的高度:

- (instancetype)initWithImage:(UIImage *)image title:(NSString*)title message:(NSString*)msg

这是我的自定义类,需要显示事件消息、标题、图像和消息。顺便说一句,只有消息部分的高度是动态的,所以我只是使用计算了这部分

[NSString boundingRectWithSize:]

事件媒体项.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

使用方法: 首先注册cell nib(Swift项目)

self.collectionView.registerNib(UINib(nibName: "VobMessagesMediaCellIncoming", bundle: nil), forCellWithReuseIdentifier: "VobMessagesMediaCellIncoming")

VobMessagesMediaCellIncoming 只是您现在正在使用的任何传入消息单元格的副本,根据我的经验,您必须复制一个具有不同标识符的新单元格,而不是对普通消息和媒体消息使用相同的 nib,否则 JSQMessageCollectionView 可能会混淆并显示异常重用单元格时的消息。

然后,在 cellForItemAtIndexPath 中,您将分叉逻辑以设置单元格的 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 但是,我无法从这些线程中获得任何有用的信息。--#

于 2016-12-05T04:37:59.543 回答
0

我建议做这样的事情

extension JSQMessagesCollectionViewCellOutgoing {
    public func messageContentSmaller() {
       self.messageBubbleContainerView?.setContentCompressionResistancePriority(UILayoutPriorityDefaultLow, forAxis: .Horizontal)

    }
}

您可能还需要 self.messageBubbleContainerView.setNeedsLayout

让我知道这是否有帮助。

于 2016-02-14T23:36:56.983 回答