ios 气泡聊天
最近做的项目里面,有几个模块用到了聊天功能和评论回复的功能,使用的频率还是很高的,所以抽时间做了这个博客,希望能给自己和别人带来方便,
具体代码如下:
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 气泡聊天的更多相关文章
- DUILIB 实现微信气泡聊天效果
最近由于项目原因,需要做一个产品内嵌的IM聊天系统.而且要象微信类似的效果:界面也要比较炫: 开始考虑用MFC,但MFC的控件自绘很麻烦,后来又考虑QT,倒是使用控件使用方便,但QT库太大,所以也放弃 ...
- 转-Android仿微信气泡聊天界面设计
微信的气泡聊天是仿iPhone自带短信而设计出来的,不过感觉还不错可以尝试一下仿着微信的气泡聊天做一个Demo,给大家分享一下!效果图如下: 气泡聊天最终要的是素材,要用到9.png文件的素材,这样气 ...
- 基于Qt的类QQ气泡聊天的界面开发
近期在写IM 聊天界面,想设计出一个类似QQ气泡聊天的样式 使用了几种办法 1:使用Qt以下的QListview来实现QQ类似效果.差强人意 2:使用QWebview载入html css样式来完毕.发 ...
- Android仿微信气泡聊天界面设计
微信的气泡聊天是仿iPhone自带短信而设计出来的,不过感觉还不错可以尝试一下仿着微信的气泡聊天做一个Demo,给大家分享一下!效果图如下: 气泡聊天最终要的是素材,要用到9.png文件的素材,这样气 ...
- 模仿QQ气泡聊天
尝试了几种方案,想模仿QQ的气泡聊天,总是不尽如意.网上倒是大把的Android和Html的例子,Delphi的没找着,只能自己试着折腾. 1. 用WebBrowser加载本地html,屡次折腾,失败 ...
- android 仿QQ气泡聊天界面
1.现在的QQ,微信等一些APP的聊天界面都是气泡聊天界面,左边是接收到的消息,右边是发送的消息, 这个效果其实就是一个ListView在加载它的Item的时候,分别用了不同的布局xml文件. 2.效 ...
- 第五十八篇、iOS 微信聊天发送小视频的秘密
对于播放视频,大家应该一开始就想到比较方便快捷使用简单的MPMoviePlayerController类,确实用这个苹果官方为我们包装好了的 API 确实有很多事情都不用我们烦心,我们可以很快的做出一 ...
- iOS UI-QQ聊天布局
一.Model BWMessage.h #import <Foundation/Foundation.h> typedef enum{ BWMessageMe = ,//表示自己 BWMe ...
- 聊天界面之气泡文本cell(一)
在实现qq聊天界面的过程中,使用UITableViewCell碰到了不少问题,这里还是记录一下以免遗忘. 气泡聊天cell的实现,网上最多的方法还是: 1.手动计算设置frame的值,文本的size使 ...
随机推荐
- HTML onmousedown 事件属性 关于鼠标按键的问题;
在项目中遇到一个问题,就是点击任意键关闭弹窗的处理:出现了一个bug:就是在angularjs项目中两个controller之间的事件跳转,使用的ng-show =“iscontext” : 如所示: ...
- eclipse偶尔会反映迟钝,直接无视其报错
比如,你在web.xml中配置了什么东西,在有的时候不一定就会立即被eclipse察觉到,即便你的配置正确了,甚至重启了几次服务器,它仍然给你报错 比如说,刚才我在web.xml中配置了一个tagli ...
- WPF 冒泡路由事件
在WPF中,例如,可以构建一个包含图形的按钮,创建一个具有文本和图片混合内容的标签,或者为了实现滚动或折叠的显示效果在一个特定的容器中放置内容.甚至可以多此重复嵌套,直到达到您所希望的层次深度. 这种 ...
- fullcalendar案例一<原>
fullcalendar是个很强大的日历控件,可以用它进行排班.排会议.拍任务,很直观,用户体验良好. 看下效果图: #parse("index/head.vm") <lin ...
- HDFS入门
HDFS入门 欢迎关注我的个人博客:http://www.cnblogs.com/yjd_hycf_space 更多大数据以及编程相关的精彩文章 为什么我们需要HDFS 文件系统由三部分组成:与文件管 ...
- Html5 小球键盘移动
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <t ...
- HTML坦克大战学习01
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <t ...
- C++构造函数后面的冒号
构造函数后加冒号是初始化表达式:有四种情况下应该使用初始化表达式来初始化成员:1:初始化const成员2:初始化引用成员3:当调用基类的构造函数,而它拥有一组参数时 4:当调用成员类的构造函数,而它拥 ...
- 关于Unity的入门游戏飞机大战的开发(上)
每个组件都是一个类的实例,要获得某个组件,要先创建一个同类型的组件类实例,然后把实例传引用过去,就可以对想要的组件实例进行操作. 做游戏一般创建一个逻辑节点,里面只管逻辑,再创建一个动画节点,里面有好 ...
- Omnigraffle快捷键
cmd+shift+. 和 cmd+shift+, 放大缩小 按住z点击鼠标是放大, z+Option是缩小 按住command双指推移 缩放 按住command,旋转物体 按住 option缩放 ...