最近做的项目里面,有几个模块用到了聊天功能和评论回复的功能,使用的频率还是很高的,所以抽时间做了这个博客,希望能给自己和别人带来方便,

具体代码如下:

1,创建model,

#import <Foundation/Foundation.h>

@interface MessageObj : NSObject

@property(nonatomic,copy)NSString *message;
@property(nonatomic,assign)BOOL isMe; @end

2,自定义cell

1)声明一个label和imageview

@property(nonatomic,strong)UIImageView *messageImg;
@property(nonatomic,strong)UILabel *messageLab;

2)初始化构造方法

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
//这里只需要初始化,不需要设置具体的坐标
self.backgroundColor = [UIColor clearColor];
self.selectionStyle = UITableViewCellSelectionStyleNone;
_messageImg = [[UIImageView alloc]init];
[self addSubview:_messageImg];
_messageLab = [[UILabel alloc]init];
_messageLab.numberOfLines = ;
[self addSubview:_messageLab];
} return self;
}

3,准备工作已做好,现在进行聊天功能的完善

1)声明所需的成员变量

@interface ViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>
{
UITextField *tf;
UIView *inputView;
UIButton *rightBtn;
UITableView *tableViews; int _count;
NSMutableArray *_datasArray;
}

2)界面的布局,做好适配

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
_datasArray = [NSMutableArray array];//这里一定要记得初始化 self.title = @"气泡聊天";
self.view.backgroundColor = [UIColor whiteColor]; tableViews = [[UITableView alloc]initWithFrame:CGRectMake(, , MainScreen_width, self.view.bounds.size.height-) style:UITableViewStylePlain];
tableViews.delegate = self;
tableViews.dataSource = self;
tableViews.tableFooterView = [[UIView alloc]init];
tableViews.separatorStyle = UITableViewCellSeparatorStyleNone;
[self.view addSubview:tableViews]; inputView = [[UIView alloc]initWithFrame:CGRectMake(, MainScreen_height - , MainScreen_width, )];
inputView.backgroundColor = RGBAColor(, , , );
[self.view addSubview:inputView]; tf = [[UITextField alloc]initWithFrame:CGRectMake(, , MainScreen_width - , )];
tf.delegate = self;
tf.returnKeyType = UIReturnKeyDefault;
[inputView addSubview:tf]; rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
rightBtn.frame = CGRectMake(MainScreen_width - -, , MainScreen_width - tf.frame.size.width, );
[rightBtn setTitle:@"发送" forState:UIControlStateNormal];
[rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[rightBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[inputView addSubview:rightBtn]; //增加监听,当键盘改变是发出消息
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; //增加监听,当键盘退出时发出消息
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

注:这里最后,声明了两个通知,这样是为了,监听键盘弹出和弹下的高度,

具体实现如下:

-(void)keyboardWillShow:(NSNotification *)hNotification
{
//获取键盘的高度
NSDictionary *userInfo = [hNotification userInfo];
NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
int height = keyboardRect.size.height;//获取到的键盘的高度
[UIView animateWithDuration:0.1 animations:^{
CGRect tableFrame = tableViews.frame;
tableFrame.size.height = MainScreen_height - height - ;
tableViews.frame = tableFrame;
CGRect rect = inputView.frame;
rect.origin.y = MainScreen_height - height - ;
inputView.frame = rect;
}]; } -(void)keyboardWillHide:(NSNotification *)hNotification
{
[UIView animateWithDuration:0.1 animations:^{
CGRect tableViewRect = tableViews.frame;
tableViewRect.size.height = MainScreen_height- ;
tableViews.frame = tableViewRect;
CGRect rect = inputView.frame;
rect.origin.y = MainScreen_height - ;
inputView.frame = rect;
}]; if (_datasArray.count > )
{
//让表的最后一行滚动到表的底部
NSIndexPath * indexPath = [NSIndexPath indexPathForRow:_datasArray.count- inSection:];
[tableViews scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
}

3)发送按钮的点击方法

-(void)btnClick:(id)sender
{
_count ++;//这里声明一个int类型的变量是为了下面区分是否是自己 //这里使用model,会很方便,单独作为对象来使用,方便进行设置
MessageObj *objets = [[MessageObj alloc]init];
objets.message = tf.text; if (objets.message != nil && [objets.message isEqualToString:@""]) {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"温馨体香" message:@"不能为空" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
[alertView show];
return;
}else
{
//这里通过第一个发送的顺序,设为自己,其他为别人,然后绑定一个bool值的状态,yes为自己,no为别人
if (_count% == ) {
objets.isMe = YES;
}else
{
objets.isMe = NO;
} [_datasArray addObject:objets];
NSLog(@"--%lu",(unsigned long)_datasArray.count);
[tableViews reloadData]; //让表的最后一行滚动到表的底部
NSIndexPath * indexPath = [NSIndexPath indexPathForRow:_datasArray.count- inSection:];
[tableViews scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; tf.text = nil;
}
}

注:这里面有比较重要的地方,代码很详细,我就不一一解释了,大家可以自己看

4)表的具体展现和自适应

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _datasArray.count;
} -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
MessageObj *object = _datasArray[indexPath.row]; CGFloat contentW = MainScreen_width - ; UIFont *fnt = [UIFont fontWithName:@"HelveticaNeue" size:18.0f]; //ios 7 以后的方法,这里得到自适应的高度,从而动态的设置cell的高度
CGRect tempRect = [object.message boundingRectWithSize:CGSizeMake(contentW, ) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil] context:nil];
CGFloat contenH = tempRect.size.height; return contenH + ;
} -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifiers = @"CELLES";
    EightyTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell) {
        
        cell = [[EightyTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifiers];
        cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    }
    
    MessageObj *object = _datasArray[indexPath.row];
    /*
     CGFloat contentW = MainScreen_width - 34;
     
     UIFont *fnt = [UIFont fontWithName:@"HelveticaNeue" size:18.0f];
     
     CGRect tempRect = [object.message boundingRectWithSize:CGSizeMake(320, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil] context:nil];
     CGFloat contenH = tempRect.size.height;
     */
    
    //在这里进行宽度和高度的自适应
    UIFont *fnt = [UIFont fontWithName:@"HelveticaNeue" size:18.0f];
    CGSize size = CGSizeMake(MainScreen_width,1000);
    CGSize labSize = [object.message sizeWithFont:fnt constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
    
    
    if (object.isMe == YES) {
        
        cell.messageLab.frame = CGRectMake(20, 0, labSize.width, labSize.height);
        cell.messageLab.textAlignment = NSTextAlignmentLeft;
        cell.messageLab.numberOfLines = 0;
        cell.messageImg.frame = CGRectMake(10, 0, labSize.width+20, labSize.height+10);
    }else
    {
        cell.messageLab.frame = CGRectMake(MainScreen_width - 20 - labSize.width, 5, labSize.width, labSize.height);
        cell.messageLab.numberOfLines = 0;
        cell.messageLab.textAlignment = NSTextAlignmentRight;
        cell.messageImg.frame = CGRectMake(MainScreen_width - 30 - labSize.width, 2, labSize.width + 20, labSize.height + 10);
    }
    
    NSString *imageName = object.isMe?@"bubbleSelf.png":@"bubble.png";
    UIImage *oldImage = [UIImage imageNamed:imageName];
    UIImage *newImage = [oldImage stretchableImageWithLeftCapWidth:18 topCapHeight:8];
    cell.messageImg.image = newImage;
    cell.messageLab.font = fnt;
    cell.messageLab.text = object.message;
    
    return  cell;
    
}

注:主要就是cellforrow方法里面的lab自适应坐标的设置,还有气泡背景图片的坐标设置,还有heightforrow里面根据lab的高度,动态判定cell的高度

效果图如下:

如需源码,可从这里下载:http://code.cocoachina.com/view/131767

ios 气泡聊天的更多相关文章

  1. DUILIB 实现微信气泡聊天效果

    最近由于项目原因,需要做一个产品内嵌的IM聊天系统.而且要象微信类似的效果:界面也要比较炫: 开始考虑用MFC,但MFC的控件自绘很麻烦,后来又考虑QT,倒是使用控件使用方便,但QT库太大,所以也放弃 ...

  2. 转-Android仿微信气泡聊天界面设计

    微信的气泡聊天是仿iPhone自带短信而设计出来的,不过感觉还不错可以尝试一下仿着微信的气泡聊天做一个Demo,给大家分享一下!效果图如下: 气泡聊天最终要的是素材,要用到9.png文件的素材,这样气 ...

  3. 基于Qt的类QQ气泡聊天的界面开发

    近期在写IM 聊天界面,想设计出一个类似QQ气泡聊天的样式 使用了几种办法 1:使用Qt以下的QListview来实现QQ类似效果.差强人意 2:使用QWebview载入html css样式来完毕.发 ...

  4. Android仿微信气泡聊天界面设计

    微信的气泡聊天是仿iPhone自带短信而设计出来的,不过感觉还不错可以尝试一下仿着微信的气泡聊天做一个Demo,给大家分享一下!效果图如下: 气泡聊天最终要的是素材,要用到9.png文件的素材,这样气 ...

  5. 模仿QQ气泡聊天

    尝试了几种方案,想模仿QQ的气泡聊天,总是不尽如意.网上倒是大把的Android和Html的例子,Delphi的没找着,只能自己试着折腾. 1. 用WebBrowser加载本地html,屡次折腾,失败 ...

  6. android 仿QQ气泡聊天界面

    1.现在的QQ,微信等一些APP的聊天界面都是气泡聊天界面,左边是接收到的消息,右边是发送的消息, 这个效果其实就是一个ListView在加载它的Item的时候,分别用了不同的布局xml文件. 2.效 ...

  7. 第五十八篇、iOS 微信聊天发送小视频的秘密

    对于播放视频,大家应该一开始就想到比较方便快捷使用简单的MPMoviePlayerController类,确实用这个苹果官方为我们包装好了的 API 确实有很多事情都不用我们烦心,我们可以很快的做出一 ...

  8. iOS UI-QQ聊天布局

    一.Model BWMessage.h #import <Foundation/Foundation.h> typedef enum{ BWMessageMe = ,//表示自己 BWMe ...

  9. 聊天界面之气泡文本cell(一)

    在实现qq聊天界面的过程中,使用UITableViewCell碰到了不少问题,这里还是记录一下以免遗忘. 气泡聊天cell的实现,网上最多的方法还是: 1.手动计算设置frame的值,文本的size使 ...

随机推荐

  1. js正则表达式判断一个字符串是否是正确的有数字和小数点组成的金钱形式和 判读数值类型的正则表达式

    function checkRates(str){    var re = /^(([1-9][0-9]*\.[0-9][0-9]*)|([0]\.[0-9][0-9]*)|([1-9][0-9]*) ...

  2. 第一个Hibernate 程序

    使用MyEclipse建立Hibernate工程 index页面的Jsp源文件 <%@ page language="java" import="java.util ...

  3. git hook部署代码

    git 提供了钩子功能,当某个操作发生时,可以执行某个动作. ftp上传时没有文件比较,虽然可以winscp提供了同步功能但是不够强大,而且文件多了,会花费比较长的时间. 1.先在主机上搭建一个git ...

  4. 【Unity笔记】物体的Transform操作:速度、旋转、平移

    例如,通过按键/摇杆来操作飞机在三维空间的飞行状态.包括速度(大小,方向).位移. public class ExampleClass : MonoBehaviour { public float s ...

  5. Spring InitializingBean和ApplicationListener<ContextRefreshedEvent>

    事件机制作为一种编程机制,在许多语言中都提供了支持.JAVA语言也不例外,java中的事件机制的参与者有3种角色: 1.event object 2.event source 3.event list ...

  6. nginx的centos和rhel的yum配置安装

    Official Red Hat/CentOS packages To add NGINX yum repository, create a file named /etc/yum.repos.d/n ...

  7. REST构架风格介绍:状态表述转移(转)

    本文总结了一些REST风格构架设计的经验,介绍了REST架构的语言生态环境,状态表述转移,无状态服务器等特点,并通过举例Google来说明REST风格的味道. REST(Representationa ...

  8. Python写自己主动化之邮件发送(匿名)

    为了可以实现邮件发送功能.首先.我们须要了解一下邮件的发送过程是什么样子的,此处不再具体说明,请大家自行搜索或查看p=438">http://www.sogouqa.com/?p=43 ...

  9. CodeIgniter(3.1.4)框架使用静态文件(js,css)

    调整目录结构: 可以在控制器中这样加载视图: * 加载url辅助类. views视图中可以这样引用静态文件: 则最终的静态文件url会生成这样:

  10. NLog 配置与使用

    有段时间没写博客了,过年放假,一直在弄CMS.什么都自己写了一遍,今天写写NLog,之前一用的log4net,感觉配置起来还是有些麻烦. NuGet 添加组件 配置 NLog.config <? ...