_chatTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 420) style:UITableViewStylePlain];
//自适应宽和高
_chatTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
//让cell直接的那条线段不显示 就是每行之间的那条线
_chatTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//设置代理
_chatTableView.delegate = self;
_chatTableView.dataSource = self;
// //把背景色清空 为了显示view的背景图片
_chatTableView.backgroundColor = [UIColor clearColor];
//
// VCChatView.m
// ZhaoXiaoLe
/*
*/
// Created by qian feng on 13-10-11.
//
//
#import "VCChatView.h"
//自定义cell类
#import "ChatCell.h"
//数据实类化
#import "ChatItem.h"
#import "ChatMessageItem.h"
#import "LoginItem.h"
#import "RegisterItem.h"
#import "DataManager.h"
@interface VCChatView ()
@end
@implementation VCChatView
{
UITableView * _chatTableView;
NSMutableArray * _chatMutableArray;
UIView * _chatBlackView;
UITextView * _chatTextView;
int _k;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
-(void)dealloc{
[_chatBlackView release];
[_chatMutableArray release];
[_chatTableView release];
[_chatTextView release];
[super dealloc];
}
#pragma mark -ZXL_创建tableView
-(void)chatCreatTable{
_chatTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 420) style:UITableViewStylePlain];
//自适应宽和高
_chatTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
//让cell直接的那条线段不显示 就是每行之间的那条线
_chatTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//设置代理
_chatTableView.delegate = self;
_chatTableView.dataSource = self;
// //把背景色清空 为了显示view的背景图片
_chatTableView.backgroundColor = [UIColor clearColor];
[self.view addSubview:_chatTableView];
}
#pragma mark - ZX_创建输入框和相应的按钮
-(void)chatCretVIew{
_chatBlackView = [[UIView alloc]initWithFrame:CGRectMake(0, 376, 320, 40)];
//++++++++++++++++++创建发送按钮+++++++++++++++++++++++++++++++++++++++++
UIButton * rightBUtton = [UIButton buttonWithType:UIButtonTypeCustom ];
[rightBUtton setImage:[UIImage imageNamed:@"comment_canSend"] forState:UIControlStateNormal];
//由于button是图片创建的 只能把一个label文字加载上面
// UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(2,2 ,36 , 26)];
// label.text = @"发送";
// label.textAlignment = NSTextAlignmentCenter;
// label.font = [UIFont systemFontOfSize:16];
// label.textColor = [UIColor grayColor];
// label.backgroundColor = [UIColor clearColor];
// [rightBUtton addSubview:label];
// [label release];
rightBUtton.titleLabel.font = [UIFont systemFontOfSize:18];
rightBUtton.bounds = CGRectMake(0, 0, 30, 30);
//因为随着字的输入 输入框会发生变化,为了让button的位置不变 用中心
rightBUtton.center = CGPointMake(290, _chatBlackView.frame.size.height/2);
[rightBUtton addTarget:self action:@selector(chatPress) forControlEvents:UIControlEventTouchUpInside];
[_chatBlackView addSubview:rightBUtton];
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//文本输入框
_chatTextView = [[UITextView alloc]initWithFrame:CGRectMake(60, 5, 198, 30)];
_chatTextView.editable =YES;
_chatTextView.font = [UIFont systemFontOfSize:20];
_chatTextView.delegate =self;
[_chatBlackView addSubview:_chatTextView];
_chatBlackView.backgroundColor = [UIColor grayColor];
[self.view addSubview:_chatBlackView];
//监听键盘输入
//事件监听中心
//设置信息接收中心 这是一个单类 //第一个参数 监听者 第二个参数 监听后执行的方法 第三个参数 监听的信息 这个信息如果触发 则执行方法
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(chatKeyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(chatKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
#pragma mark - ZXL聊天窗口随着内容的输入变高的功能 实现中 有bug
/*
-(void)textViewDidChange:(UITextView *)textView{
NSLog(@"text = %d",(int)[_chatTextView.text sizeWithFont:[UIFont systemFontOfSize:20]].width);
NSLog(@"bla= %d",(int)_chatTextView.frame.size.width);
int i = (20+(int)[_chatTextView.text sizeWithFont:[UIFont systemFontOfSize:20]].width)/(int)_chatTextView.frame.size.width;
CGRect tableView = _chatTextView.frame;
CGRect frametext = _chatTextView.frame;
CGRect frame = _chatBlackView.frame;
CGRect frameBlac;
CGRect frameTable;
if (i>_k&&_chatTextView.text.length!=0) {
_k++;
NSLog(@"%d",i);
frameTable = CGRectMake(tableView.origin.x, tableView.origin.y-30*i, tableView.size.width, tableView.size.height);
frametext = CGRectMake(60, 5, 198, 30+30*i) ;
frameBlac = CGRectMake(frame.origin.x, frame.origin.y-30*i, frame.size.width, frame.size.height+30*i);
_chatTableView.frame = frameTable;
_chatTextView.frame = frametext;
_chatBlackView.frame = frameBlac;
}
// _chatTableView.frame = frameTable;
// _chatTextView.frame = frametext;
// _chatBlackView.frame = frameBlac;
}
*/
#pragma mark - ZXL_发送按钮触发事件
-(void)chatPress{
//判断是否有输入,有的话才执行,没有不输出
if (_chatTextView.text.length<1) {
return;
}
//把数据存入实类化的类
[mTimer setFireDate:[NSDate distantFuture]];
ChatMessageItem * item11 = [[DataManager sharManager]objectForKey:EMAIL_CHAT_VIEW_URL];
NSString * userId = [item11.data objectForKey:@"user_id"];
NSLog(@"给谁发信息%@",userId);
NSString * str = [_chatTextView.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString * body = [NSString stringWithFormat:@"info%%5Bmessage%%5D=%@",str];
NSMutableData * data =[NSMutableData dataWithData:[body dataUsingEncoding:NSUTF8StringEncoding]];
LoginItem * item = [[DataManager sharManager] objectForKey:LOGIN_URL];
NSString * rUrl = [NSString stringWithFormat:SEND_MESSAGE_URL ,userId,item.login_str];
if (item.status==0) {
RegisterItem * re = [[DataManager sharManager]objectForKey:REGISTER_URL];
NSString * ruu = [NSString stringWithFormat:SEND_MESSAGE_URL,userId,re.login_str];
[[DataManager sharManager] addGetTask:SEND_MESSAGE_URL andRealurl:ruu apiType:SEND_MESSAGE_TYPE andData:data ContentType:CONTENT_TYPE];
return;
}
[[DataManager sharManager] addGetTask:SEND_MESSAGE_URL andRealurl:rUrl apiType:SEND_MESSAGE_TYPE andData:data ContentType:CONTENT_TYPE];
}
#pragma mark - ZXL_响应回应的输出
-(void)aother{
ChatItem * chat = [[ChatItem alloc]init];
chat.isSelf = NO;
chat.content = @"对不起,我现在不在,有事请稍后联系";
[_chatMutableArray addObject:chat];
[chat release];
//添加一行 怎么在tableview 中只添加一行
//这个indexPath表示的是最后一行的位置
NSIndexPath * path = [NSIndexPath indexPathForRow:_chatMutableArray.count-1 inSection:0];
[_chatTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:path] withRowAnimation:UITableViewRowAnimationAutomatic];
[_chatTableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
//监听键盘将要出现事件
-(void)chatKeyBoardWillShow:(NSNotification*)noti{
//获取接盘的大小
CGSize size = [[noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size ;
//重新布置tableviehe下面输入框的位置,来适应键盘的变化
_chatTableView.frame = CGRectMake(0, 0, 320, 376-size.height);
_chatBlackView.frame = CGRectMake(0, 376-size.height, 320, 40) ;
//这里的这个判断是为了调掉一个bug 为了使每次键盘弹出的时候都能让tableview的cell显示处最后的几个 判断是为了防止第一次数组换是0,可能奔溃;
if (_chatMutableArray.count!=0) {
NSIndexPath * path = [NSIndexPath indexPathForRow:
_chatMutableArray.count-1
inSection:0];
[_chatTableView scrollToRowAtIndexPath:
path
atScrollPosition:
UITableViewScrollPositionBottom
animated:
NO];
}
}
-(void)chatKeyboardWillHide:(NSNotification*)noti{
//归位回到从前的位置
_chatBlackView.frame = CGRectMake(0, 376, 320 ,40 );
_chatTableView.frame =CGRectMake(0, 0, 320, 376);
}
-(void)backClick:(UIBarButtonItem*)but{
self.tabBarController.tabBar.hidden = NO;
[self.navigationController popViewControllerAnimated:YES];
}
-(void)receiveMess{
ChatMessageItem* item1=[[DataManager sharManager]objectForKey:EMAIL_CHAT_VIEW_URL];
NSString* userId =[item1.data objectForKey:@"user_id"];
LoginItem * item = [[DataManager sharManager] objectForKey:LOGIN_URL];
NSString * rUrl = [NSString stringWithFormat:EMAIL_CHAT_VIEW_URL ,userId,item.login_str];
if (item.status==0) {
RegisterItem * re = [[DataManager sharManager]objectForKey:REGISTER_URL];
NSString * ruu = [NSString stringWithFormat:EMAIL_CHAT_VIEW_URL,userId,re.login_str];
[[DataManager sharManager] addGetTask:EMAIL_CHAT_VIEW_URL
apiType:EMAIL_CHAT_VIEW_TYPE andRealUrl:ruu];
return;
}
[[DataManager sharManager] addGetTask:EMAIL_CHAT_VIEW_URL
apiType:EMAIL_CHAT_VIEW_TYPE andRealUrl:rUrl];
}
- (void)viewDidLoad
{
[super viewDidLoad];
_chatMutableArray = [[NSMutableArray alloc]init];
[self addBarButtonItem:nil imageName:@"back" position:YES method:@selector(backClick:)];
//设置聊天背景图片 需要把tableView的背景色设置为透明的
//这个背景可以自己设置图片
//
// if (!mTimer) {
// mTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(receiveMess) userInfo:nil repeats:YES];
// }
self.view.backgroundColor = [UIColor whiteColor];
[self chatCretVIew];
[self chatCreatTable];
ChatMessageItem* item=[[DataManager sharManager]objectForKey:EMAIL_CHAT_VIEW_URL];
NSString* user_id =[item.data objectForKey:@"user_id"];
NSArray * messArray = [item.data objectForKey:@"message"];
self.navigationItem.title = [item.data objectForKey:@"username"];
for (NSDictionary * dic in messArray) {
NSString * user = [dic objectForKey:@"sender_id"];
if ([user intValue]==[user_id intValue]) {
ChatItem * chat = [[ChatItem alloc]init];
chat.isSelf = NO;
chat.content = [dic objectForKey:@"message"];
[_chatMutableArray addObject:chat];
[chat release];
}else{
ChatItem * chat = [[ChatItem alloc]init];
chat.isSelf = YES;
chat.content = [dic objectForKey:@"message"];
[_chatMutableArray addObject:chat];
[chat release];
}
}
//为了实现点击任何一处都可以实现键盘的收回去,我使用了一个手势,用手势来实现这个功能
UITapGestureRecognizer * tapOne = [[UITapGestureRecognizer alloc]init];
//点击次数 手指点击几次屏幕从而有效
tapOne.numberOfTapsRequired = 1;
//点击的手指个数
tapOne.numberOfTouchesRequired = 1;
//添加点击函数
[tapOne addTarget:self action:@selector(click)];
[_chatTableView addGestureRecognizer:tapOne];
[tapOne release];
}
//手势方法,收回键盘
-(void)click{
[_chatTextView resignFirstResponder];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//获取大小 让每行的高度都可以适应输入气泡的大小
ChatItem * chat = [_chatMutableArray objectAtIndex:indexPath.row];
CGSize size = [chat.content sizeWithFont:[UIFont systemFontOfSize:18] constrainedToSize:CGSizeMake(250, 1000) lineBreakMode:NSLineBreakByCharWrapping];
return size.height+25;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectio{
return _chatMutableArray.count;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
ChatCell * cell =[_chatTableView dequeueReusableCellWithIdentifier:@"ID"];
if (cell==nil) {
cell = [[[ChatCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ID"]autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.selected = YES;
}
ChatItem * chat = [_chatMutableArray objectAtIndex:indexPath.row];
//计算文本的高度
//取得字符串的大小 //第一个参数:计算字符串的字体
//第二个参数 字符串最大的高度和宽度 上限
//第三个参数 换行模式
CGSize size = [chat.content sizeWithFont:[UIFont systemFontOfSize:18] constrainedToSize:CGSizeMake(250, 1000) lineBreakMode:NSLineBreakByCharWrapping];
//如果这个信息是我自己发送的
//isSelf就在这里发挥作用了
if (chat.isSelf) {
cell.rightLabel.text = chat.content;
cell.leftView.hidden=YES;
cell.rightView.hidden = NO;
cell.rightLabel.frame = CGRectMake(15, 10, size.width, size.height);
cell.rightView.frame = CGRectMake(320-10-35-size.width, 5, size.width+35, 25+size.height);
}else{
//如果这个信息是别人发过来的
cell.leftLabel.text = chat.content;
cell.leftView.hidden = NO;
cell.rightView.hidden = YES;
cell.leftLabel.frame = CGRectMake(20, 10, size.width, size.height);
cell.leftView.frame = CGRectMake(10, 5, size.width+35, size.height+25);
}
return cell;
}
-(void)sendMessage:(NSNotification*)not{
NSString * st = [[DataManager sharManager]objectForKey:not.name];
[mTimer setFireDate:[NSDate distantPast]];
if ([st intValue]==1) {
ChatItem * chat = [[ChatItem alloc]init];
chat.isSelf = YES;//判断信息来源
chat.content = _chatTextView.text;//信息内容
[_chatMutableArray addObject:chat];
[chat release];
//添加一行 怎么在tableview 中只添加一行
//这个indexPath表示的是最后一行的位置
//第一个参数 添加的是第几行 第二个参数 在那个段落中
//我们要把信息添加到最后的cell,所以应该是最后一行
NSIndexPath * path = [NSIndexPath indexPathForRow:_chatMutableArray.count-1 inSection:0];
//添加上去 把新的的cell添加到tableView上去
//第一个参数 是添加的行数数组 注意是个数组
//第二个参数添加动画
[_chatTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:path] withRowAnimation:UITableViewRowAnimationAutomatic];
//显示出来 把新添加的参数显示出来
[_chatTableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
else{
UIAlertView * al = [[UIAlertView alloc]initWithTitle:@"警告" message:@"信息发送失败" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
[al show];
[al release];
}
_chatTextView.text = nil;
}
-(void)reload:(NSNotification*)not{
ChatMessageItem* item=[[DataManager sharManager]objectForKey:EMAIL_CHAT_VIEW_URL];
[_chatMutableArray removeAllObjects];
NSString* user_id =[item.data objectForKey:@"user_id"];
NSArray * messArray = [item.data objectForKey:@"message"];
self.navigationItem.title = [item.data objectForKey:@"username"];
for (NSDictionary * dic in messArray) {
NSString * user = [dic objectForKey:@"sender_id"];
if ([user intValue]==[user_id intValue]) {
ChatItem * chat = [[ChatItem alloc]init];
chat.isSelf = NO;
chat.content = [dic objectForKey:@"message"];
[_chatMutableArray addObject:chat];
[chat release];
}else{
ChatItem * chat = [[ChatItem alloc]init];
chat.isSelf = YES;
chat.content = [dic objectForKey:@"message"];
[_chatMutableArray addObject:chat];
[chat release];
[_chatTableView reloadData];
}
}
}
-(void)viewWillAppear:(BOOL)animated{
[self addMessage:SEND_MESSAGE_URL selector:@selector(sendMessage:)];
[self addMessage:EMAIL_CHAT_VIEW_URL selector:@selector(reload:)];
}
-(void)viewWillDisappear:(BOOL)animated{
[self removeMessage:SEND_MESSAGE_URL];
[self removeMessage:EMAIL_CHAT_VIEW_URL];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end