iOS 環(huán)信自定義cell

環(huán)信3.x自定義表情實現(xiàn)https://www.tuicool.com/articles/YVrmY33

很久沒有寫簡書了,首先給張效果圖,有自定義的cell,有cell的點擊事件,有自定義的chatBarMoreView:

推薦的做法
WechatIMG1.jpeg

//先注冊
    [self.tableView registerNib:[UINib nibWithNibName:@"ClubRoomChatNoticeCell" bundle:nil] forCellReuseIdentifier:@"ClubRoomChatNoticeCell"];

- (UITableViewCell *)messageViewController:(UITableView *)tableView cellForMessageModel:(id<IMessageModel>)model
{
    if ([[model.message.ext objectForKey:@"type"] isEqualToString:@"announced"]) {
        ClubChatOpenPrizeCell *cell = (ClubChatOpenPrizeCell *)[tableView dequeueReusableCellWithIdentifier:@"ClubChatOpenPrizeCell"];
        cell.title.text = [NSString stringWithFormat:@"%@",model.text];
        return cell;
    }
     return nil;
}

以下這種做法不推薦

D207671342CDCCAD9A187B411A7FC99A.png

我的思路是直接修改源碼的(如果不修改源碼能實現(xiàn)最好)大家可以借鑒處理的過程及思路,如有不妥之處,請大家及時留言告知

環(huán)信初始化

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    EMOptions *options = [EMOptions optionsWithAppkey:@"Xxxxxx"];
    options.enableConsoleLog = NO;
    [[EMClient sharedClient] initializeSDKWithOptions:options];
    //監(jiān)聽自動登錄的狀態(tài)
    [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];

    return YES;
}

- (void)didConnectionStateChanged:(EMConnectionState)aConnectionState{
    if (aConnectionState == EMConnectionConnected) {
        NSLog(@"網(wǎng)絡(luò)連接成功");
    }else{
        NSLog(@"網(wǎng)絡(luò)斷開");
        //監(jiān)聽網(wǎng)絡(luò)狀態(tài)(這里通知的目地是檢測到如果沒網(wǎng)絡(luò)的情況下,修改Navigation.title的值)
    }
}

- (void)connectionStateDidChange:(EMConnectionState)aConnectionState{
    NSLog(@"斷線重連不需要其他操作%u",aConnectionState);
}

- (void)userAccountDidLoginFromOtherDevice{
    NSLog(@"在別的設(shè)備上登陸了");
}

- (void)autoLoginDidCompleteWithError:(EMError *)aError{
    NSLog(@"自動登錄完成時的回調(diào)");
}

- (void)messagesDidReceive:(NSArray *)aMessages{
    NSLog(@"收到一條新的消息");
      for (EMMessage *message in aMessages) {
          NSLog(@"%@",message);
      }
}

創(chuàng)建單聊頁面,主要是發(fā)送擴展消息,

//
//  SingleChatViewController.m
//  TextChat
//
//  Created by apple on 2017/10/18.
//  Copyright ? 2017年 劉龍飛. All rights reserved.
//

#import "SingleChatViewController.h"

@interface SingleChatViewController ()<EaseChatBarMoreViewDelegate,EaseMessageViewControllerDelegate,EaseMessageViewControllerDataSource,EaseMessageCellDelegate>

@end

@implementation SingleChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.delegate = self;
    self.dataSource = self;
    self.chatBarMoreView.delegate = self;
    self.showRefreshHeader = YES;
    
    //去掉多余的按鈕
    [self.chatBarMoreView removeItematIndex:0];
    [self.chatBarMoreView removeItematIndex:0];
    [self.chatBarMoreView removeItematIndex:0];
    [self.chatBarMoreView removeItematIndex:0];
    [self.chatBarMoreView removeItematIndex:0];

    //自定義按鈕
    [self.chatBarMoreView insertItemWithImage:[UIImage imageNamed:@"wwww"] highlightedImage:[UIImage imageNamed:@"wwwwl"] title:@"就"];
    [self.chatBarMoreView insertItemWithImage:[UIImage imageNamed:@"wwww"] highlightedImage:[UIImage imageNamed:@"wwww"] title:@"這樣"];
    [self.chatBarMoreView insertItemWithImage:[UIImage imageNamed:@"wwww"] highlightedImage:[UIImage imageNamed:@"wwww"] title:@"被你"];
    [self.chatBarMoreView insertItemWithImage:[UIImage imageNamed:@"wwww"] highlightedImage:[UIImage imageNamed:@"wwww"] title:@"征服"];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:(UIBarButtonSystemItemAdd) target:self action:@selector(touchRightButton)];
}

#pragma mark - EaseChatBarMoreViewDelegate

- (void)moreView:(EaseChatBarMoreView *)moreView didItemInMoreViewAtIndex:(NSInteger)index{
    NSLog(@"點擊自定義按鈕----%ld",(long)index);
}

#pragma mark - EaseMessageViewControllerDataSource

///消息顯示用戶昵稱和頭像。
//- (id<IMessageModel>)messageViewController:(EaseMessageViewController *)viewController
//                           modelForMessage:(EMMessage *)message{
//    id<IMessageModel> model = nil;
//    model = [[EaseMessageModel alloc] initWithMessage:message];
//    model.avatarImage = [UIImage imageNamed:@"EaseUIResource.bundle/user"];//默認頭像
//    model.nickname = @"";//用戶昵稱
//    if (message.direction == EMMessageDirectionSend) {
//        NSString *headImg = [NSString stringWithFormat:@"%@%@",FILE_PATH,[ToolsManager loginUser].headImage];
//        model.avatarURLPath = headImg;
//    }
//    else if (message.direction == EMMessageDirectionReceive) {
//        NSString *headImg = [NSString stringWithFormat:@"%@%@",FILE_PATH,_relatives.imagePath];
//        model.avatarURLPath = headImg;
//    }
//    return model;
//}


#pragma mark - EaseMessageViewControllerDelegate

- (UITableViewCell *)messageViewController:(UITableView *)tableView cellForMessageModel:(id<IMessageModel>)model
{
    if ([model.message.ext objectForKey:@"msgtype"]) {
        NSString *CellIdentifier = [EaseMessageCell cellIdentifierWithModel:model];
        EaseMessageCell *cell = (EaseMessageCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[EaseMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier model:model];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.model = model;
        cell.delegate = self;
    }
    return nil;
}


- (CGFloat)messageViewController:(EaseMessageViewController *)viewController
           heightForMessageModel:(id<IMessageModel>)messageModel
                   withCellWidth:(CGFloat)cellWidth
{
    if ([messageModel.message.ext objectForKey:@"msgtype"]) {
        return 110;
    }
    return 0.f;
}

-(void)messageCellSelected:(id<IMessageModel>)model{
    if ([model.message.ext objectForKey:@"msgtype"]) {
        NSLog(@"------你點了自定義cell------");
    }
}

//長按收拾回調(diào)樣例:
- (BOOL)messageViewController:(EaseMessageViewController *)viewController
   canLongPressRowAtIndexPath:(NSIndexPath *)indexPath
{
    //樣例給出的邏輯是所有cell都允許長按
    return YES;
}

- (void)messagesDidRead:(NSArray *)aMessages{
    NSLog(@"已讀回執(zhí)");
}

#pragma mark - Private

-(void)touchRightButton{
    NSDictionary *messageExt = @{
                                 @"msgtype":@"025",
                                 @"userId":@"chenchenchenchen",
                                 @"userHeadImg":@"sisisisi",
                                 @"userName":@"yanyanyanyanyan我是自定義的cell"
                                 };
    
    [self sendTextMessage:@"我可以永遠笑著扮演你的配角 在你的背后自己煎熬 如果你不想要  想退出要趁早" withExt:messageExt];
}
@end

仿照環(huán)信的cell寫一個EaseBubbleView的分類

7059D1AB-3B8F-49FB-AE47-A1A7B587C7C4.png
import "EaseBubbleView.h"

@interface EaseBubbleView (TopicText)

/*!
 @method
 @brief 構(gòu)建文本類型消息氣泡視圖
 @discussion
 @result
 */
- (void)setupTextBubbleViewTopic;

/*!
 @method
 @brief 變更文本類型消息氣泡的邊距,并更新改子視圖約束
 @discussion
 @param margin 氣泡邊距
 @result
 */
- (void)updateTextMarginTopic:(UIEdgeInsets)margin;

@end

#import "EaseBubbleView+Text.h"

@implementation EaseBubbleView (Text)

#pragma mark - private

- (void)_setupTextBubbleMarginConstraintsTopic
{
    NSLayoutConstraint *marginTopConstraint = [NSLayoutConstraint constraintWithItem:self.textLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.backgroundImageView attribute:NSLayoutAttributeTop multiplier:1.0 constant:self.margin.top];
    NSLayoutConstraint *marginLeftConstraint = [NSLayoutConstraint constraintWithItem:self.textLabel attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.backgroundImageView attribute:NSLayoutAttributeRight multiplier:1.0 constant:-self.margin.right];
    NSLayoutConstraint *marginRightConstraint = [NSLayoutConstraint constraintWithItem:self.textLabel attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.backgroundImageView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:self.margin.left];
    NSLayoutConstraint *marginRightConstraintHeight = [NSLayoutConstraint constraintWithItem:self.textLabel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.backgroundImageView attribute:NSLayoutAttributeHeight multiplier:0.5 constant:0];

    [self.marginConstraints removeAllObjects];
    [self.marginConstraints addObject:marginTopConstraint];
    [self.marginConstraints addObject:marginLeftConstraint];
    [self.marginConstraints addObject:marginRightConstraint];
    [self.marginConstraints addObject:marginRightConstraintHeight];

    [self addConstraints:self.marginConstraints];
}

- (void)_setupTextBubbleConstraintsTopic
{
    [self _setupTextBubbleMarginConstraintsTopic];
    //增加新控件約束
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.myTextLabel attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.backgroundImageView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-10]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.myTextLabel attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.textLabel attribute:NSLayoutAttributeRight multiplier:1.0 constant:-self.margin.right]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.myTextLabel attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.textLabel attribute:NSLayoutAttributeLeft multiplier:1.0 constant:self.margin.left]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.myTextLabel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.backgroundImageView attribute:NSLayoutAttributeHeight multiplier:0.3 constant:0]];
}

#pragma mark - public

- (void)setupTextBubbleViewTopic
{
    self.textLabel = [[UILabel alloc] init];
    self.textLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.textLabel.backgroundColor = [UIColor clearColor];
    self.textLabel.numberOfLines = 2;
    [self.backgroundImageView addSubview:self.textLabel];
    
    // 新的UI控件
    self.myTextLabel = [[UILabel alloc]init];
    self.myTextLabel.font = [UIFont systemFontOfSize:12];
    self.myTextLabel.backgroundColor = [UIColor orangeColor];
    self.myTextLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.backgroundImageView addSubview:self.myTextLabel];
    [self _setupTextBubbleConstraintsTopic];
}

- (void)updateTextMarginTopic:(UIEdgeInsets)margin
{
    if (_margin.top == margin.top && _margin.bottom == margin.bottom && _margin.left == margin.left && _margin.right == margin.right) {
        return;
    }
    _margin = margin;
    
    [self removeConstraints:self.marginConstraints];
    [self _setupTextBubbleMarginConstraintsTopic];
}

@end

然后在EaseMessageCell里仿寫環(huán)信的cell,判斷是不是擴展消息,

//渲染
  case EMMessageBodyTypeText:
            {
                if ([model.message.ext objectForKey:@"msgtype"]) {
                    [_bubbleView setupTextBubbleViewTopic];
                    _bubbleView.textLabel.font = _messageTextFont;
                    _bubbleView.textLabel.textColor = _messageTextColor;
                }else{
                    [_bubbleView setupTextBubbleView];
                    _bubbleView.textLabel.font = _messageTextFont;
                    _bubbleView.textLabel.textColor = _messageTextColor;
                }
            }
                break;

//數(shù)據(jù)模型
 case EMMessageBodyTypeText:
            {
                if ([self.model.message.ext objectForKey:@"msgtype"]) {
                    _bubbleView.textLabel.attributedText = [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:model.text textFont:self.messageTextFont];
                    _bubbleView.myTextLabel.text = [self.model.message.ext objectForKey:@"userName"];
                }else{
                    _bubbleView.textLabel.attributedText = [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:model.text textFont:self.messageTextFont];
                }
            }
                break;

//跟新約束
case EMMessageBodyTypeText:
            {
                if ([self.model.message.ext objectForKey:@"msgtype"]) {
                    [_bubbleView updateTextMarginTopic:_bubbleMargin];
                }else{
                    [_bubbleView updateTextMargin:_bubbleMargin];
                }
            }
                break;

//cell的點擊事件
case EMMessageBodyTypeText:
            {
                if ([_delegate respondsToSelector:@selector(messageCellSelected:)]) {
                    [_delegate messageCellSelected:_model];
                }
            }
                break;

//獲取cell的重用標識
case EMMessageBodyTypeText:
                if ([model.message.ext objectForKey:@"msgtype"]) {
                    cellIdentifier = EaseMessageCellIdentifierSendTextTTopic;
                }else{
                    cellIdentifier = EaseMessageCellIdentifierSendText;
                }
                break;
case EMMessageBodyTypeText:
                if ([model.message.ext objectForKey:@"msgtype"]) {
                    cellIdentifier = EaseMessageCellIdentifierRecvTextTTopic;
                }else{
                    cellIdentifier = EaseMessageCellIdentifierRecvText;
                }
                break;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容