聊天界面.m文件

#import "ChatViewController.h"

#import "ChatMessage.h"

#import "EGODatabase.h"

#import "MessageCell.h"

#import "MessageFrame.h"

#import "IQKeyboardManager.h"

#define ScreenHeight [[UIScreen mainScreen]bounds].size.height

#define ScreenWidth [[UIScreen mainScreen]bounds].size.width

@interface ChatViewController ()

{

NSMutableArray *arrayChatMessage;

NSMutableArray* arrayMessagesFrame;

}

//@property (strong, nonatomic) IBOutlet UIScrollView *scroll;

@property(nonatomic,strong)NSArray* emos;

@end

@implementation ChatViewController

#pragma mark - View lifecycle

- (void)setTitle:(NSString *)title

{

[super setTitle:title];

UILabel *titleView = (UILabel *)self.navigationItem.titleView;

if (!titleView) {

titleView = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, self.view.frame.size.width*2/5, 44)];

titleView.backgroundColor = [UIColor clearColor];

titleView.font = [UIFont fontWithName:@"HelveticaNeue" size:16];

titleView.textColor = [UIColor whiteColor];

titleView.textAlignment = UITextAlignmentCenter;

self.navigationItem.titleView = titleView;

}

titleView.text = title;

[titleView sizeToFit];

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

if (self) {

// Custom initialization

}

return self;

}

- (void)viewDidLoad

{

[super viewDidLoad];

[self setTitle:self.msg.strContactName];

//表情窗口初始化

//    self.scroll.frame = CGRectMake(0, 0 - 200, ScreenWidth, 200);

CGSize viewSize = [[UIScreen mainScreen] bounds].size;

UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"bg2.png"]];

[image setFrame:CGRectMake(0, 0, viewSize.width, viewSize.height)];

[self.view addSubview:image];

[self.view sendSubviewToBack:image];

[self.navigationController.navigationBar setBackgroundImage:[UIImage new]

forBarMetrics:UIBarMetricsDefault];

self.navigationController.navigationBar.shadowImage = [UIImage new];

self.navigationController.navigationBar.translucent = YES;

self.tableChat.backgroundColor = [UIColor clearColor];

// Do any additional setup after loading the view.

if (!arrayMessagesFrame) {

arrayMessagesFrame = [[NSMutableArray alloc]init];

}

//载入本地历史消息

[self loadChatMessage];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];

//设置textField输入起始位置

self.messageField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];

self.messageField.leftViewMode = UITextFieldViewModeAlways;

self.messageField.delegate = self;

[self registerEvents];

CGRect frame = self.bottomBar.frame;

frame.origin.y = self.view.frame.size.height - 44;

[self.bottomBar setFrame:frame];

//self.messageField.text = [NSString stringWithFormat:@"\t/微笑\t"];

if (arrayMessagesFrame.count > 0) {

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:arrayMessagesFrame.count - 1 inSection:0];

[self.tableChat scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

}

#ifdef __IPHONE_5_0

float version = [[[UIDevice currentDevice] systemVersion] floatValue];

if (version >= 5.0) {

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardFrameDidChange:) name:UIKeyboardDidChangeFrameNotification object:nil];

}

#endif

//表情列表解析

//    NSString* path=[[NSBundle mainBundle]pathForResource:@"emoticons" ofType:@"plist"];

//    self.emos=[NSArray arrayWithContentsOfFile:path];

//    for (int i=0; i<self.emos.count; i++) {

//        NSDictionary* dic=self.emos[i];

//        NSString* emoName=[dic objectForKey:@"png"];

//        UIImage* image=[UIImage imageNamed:emoName];

//        UIButton* btn=[[UIButton alloc]initWithFrame:CGRectMake(i%8*40, i/8*40, 40, 40)];

//        btn.tag=i;

//        [btn setImage:image forState:UIControlStateNormal];

//        [btn addTarget:self action:@selector(showName:) forControlEvents:UIControlEventTouchUpInside];

//        [self.scroll addSubview:btn];

//    }

//    self.scroll.contentSize=CGSizeMake(self.view.bounds.size.width, self.emos.count/8*40);

}

//自定义表情方法

//-(void)showName:(UIButton*)sender{

//    NSDictionary* emoDic=[self.emos objectAtIndex:sender.tag];

//    NSString* text=[emoDic objectForKey:@"chs"];

//

//    self.messageField.text = [NSString stringWithFormat:@"%@%@",self.messageField.text,text];

//

//}

#pragma mark - 键盘处理

#pragma mark 键盘即将显示

-(void)keyBoardFrameDidChange:(NSNotification *)note

{

//    NSDictionary *userInfo = [notification userInfo];

//    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];

//    CGRect keyboardRect = [aValue CGRectValue];

//    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];

//    NSTimeInterval animationDuration;

//    [animationDurationValue getValue:&animationDuration];

CGSize size = [[UIScreen mainScreen] bounds].size;//获取屏幕的尺寸;

CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];//得到键盘的高度;

CGFloat ty = size.height - rect.size.height;//

[UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{

//frame.size.height -= rect.size.height;

if (rect.origin.y != size.height) {

CGRect frame = self.tableChat.frame;

frame.size.height = size.height - rect.size.height - 105;//屏幕高度减去键盘高度减去输入框高度,就是新的table的高度,再赋给table,

[self.bottomBar setFrame:CGRectMake(0, ty-40, 320, 40)];

[self.tableChat setFrame:frame];

}

else{

CGRect frame = self.tableChat.frame;

frame.size.height = size.height - 40;

[self.bottomBar setFrame:CGRectMake(0, size.height-40, ScreenWidth, 40)];

}

//        if (self.bottomBar.frame.origin.y == size.height - 40) {

//            [self.bottomBar setFrame:CGRectMake(0, ty-40, 320, 40)];

//        }

//        else{

//            [self.bottomBar setFrame:CGRectMake(0, size.height - 40, ScreenWidth, 40)];

//        }

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:arrayMessagesFrame.count - 1 inSection:0];

if (arrayMessagesFrame.count== 0) {

return ;

}

else

{

[self.tableChat scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

}

}];

}

- (void)keyBoardWillShow:(NSNotification *)note{

CGSize size = [[UIScreen mainScreen] bounds].size;

CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];

CGFloat ty = size.height - rect.size.height;

[UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{

CGRect frame = self.tableChat.frame;

//frame.size.height -= rect.size.height;

//frame.size.height = size.height - rect.size.height -40;

frame.size.height = size.height - rect.size.height - 105;

[self.tableChat setFrame:frame];

[self.bottomBar setFrame:CGRectMake(0, ty-40, 320, 40)];

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:arrayMessagesFrame.count - 1 inSection:0];

if (arrayMessagesFrame.count== 0) {

return ;

}

else

{

[self.tableChat scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

}

}];

//[self.navigationController.navigationBar setHidden:YES];

}

#pragma mark 键盘即将退出

- (void)keyBoardWillHide:(NSNotification *)note{

CGSize size = [[UIScreen mainScreen] bounds].size;

CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];

CGFloat ty = size.height - rect.size.height;

[UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{

CGRect frame = self.tableChat.frame;

frame.size.height += rect.size.height - 60;

[self.tableChat setFrame:frame];

[self.bottomBar setFrame:CGRectMake(0, size.height-40, 320, 40)];

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:arrayMessagesFrame.count - 1 inSection:0];

if (arrayMessagesFrame.count== 0) {

return ;

}

else

{

[self.tableChat scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

}

}];

}

#pragma mark - 文本框代理方法

#pragma mark 点击textField键盘的回车按钮

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

NSString *content = textField.text;

if ([content isEqualToString:@""]) {

return NO;

}

[self addMessageWithContent:content type:MessageTypeMe];

NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];

NSString* strUid = [pref stringForKey:@"uid"];

//NSString *strFrom = @"andy";

// NSString *strTo   = @"andy";

NSString *strMsg = [NSString stringWithFormat:@"{\"type\":\"chat\",\"from\":\"%@\",\"to\":\"%@\",\"msg\":\"%@\"}",strUid,self.msg.strContact,content];

NSLog(@"input message:%@",strMsg);

[[NSNotificationCenter defaultCenter] postNotificationName:@"AppSendMessage" object:strMsg];

[self.tableChat reloadData];

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:arrayMessagesFrame.count - 1 inSection:0];

[self.tableChat scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

self.messageField.text = nil;

return YES;

}

#pragma mark 给数据源增加内容

- (void)addMessageWithContent:(NSString *)content type:(MessageType)type{

MessageFrame *mf = [[MessageFrame alloc] init];

ChatMessage *message = [[ChatMessage alloc] init];

message.strMessage = content;

message.strContact = self.msg.strContact;

message.strContactName = self.msg.strContactName;

message.strTimeStamp = [self generateTimeStamp];

message.type = type;

message.strContactIcon = [self getContactAvatar:self.msg.strContact];

mf.message = message;

mf.showTime = YES;

[arrayMessagesFrame addObject:mf];

//   [self saveMessage:msg];

}

- (NSString*)getContactAvatar:(NSString*)contactId

{

return @"defaultAvatar";

/*    if ([contact.strAvatar isEqualToString:@""]) {

cell.imageView.image = [UIImage imageNamed:@"defaultAvatar"];

}

else

{

NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@",contact.strAvatar]];

BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];

if(!fileExists)

{

cell.imageView.image = [UIImage imageNamed:@"defaultAvatar"];

[self downloadAvatar:contact];

}

else

{

cell.imageView.image = [UIImage imageWithContentsOfFile:filePath];

}

}*/

}

- (void)loadChatMessage

{

if (!arrayChatMessage) {

arrayChatMessage = [[NSMutableArray alloc]init];

}

//    NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];

//    NSString *strMsgID = [pref valueForKey:@"MSGID"];

EGODatabase* database = [EGODatabase databaseWithPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/database.db"]];

//查询最新的消息,展示在首页聊天中,点击某一个聊天再查询该聊天下的所有历史消息

NSString *sqlQuery = [[NSString alloc]initWithFormat:@"select * from chatmessage where contact = ‘%@‘  order by timestamp",self.msg.strContact];

NSLog(@"%@",sqlQuery);

int i = 1;

EGODatabaseResult *result = [database executeQuery:sqlQuery];

for(EGODatabaseRow* row in result) {

MessageFrame *messageFrame = [[MessageFrame alloc] init];

ChatMessage *msg = [[ChatMessage alloc]init];

msg.strContact = [row stringForColumn:@"contact"];

msg.strContactIcon = @"defaultAvatar";

msg.strMessage = [row stringForColumn:@"message"];

msg.strTimeStamp = [row stringForColumn:@"timestamp"];

msg.type         = [row intForColumn:@"type"];

[arrayChatMessage insertObject:msg atIndex:0];

messageFrame.message = msg;

messageFrame.showTime = YES;

[arrayMessagesFrame addObject:messageFrame];

i = !i;

NSLog(@"chatview::load message:%@",msg.strMessage);

}

[database close];

}

- (void)registerEvents {

// Register the analytics event that are going to be tracked by Baker.

NSArray *analyticEvents = [NSArray arrayWithObjects:

@"AppReceiveNewMessage",

nil];

for (NSString *eventName in analyticEvents) {

[[NSNotificationCenter defaultCenter] addObserver:self

selector:@selector(receiveEvent:)

name:eventName

object:nil];

}

}

- (void)receiveEvent:(NSNotification *)notification {

// If you want, you can handle differently the various events

if ([[notification name] isEqualToString:@"AppReceiveNewMessage"]) {

NSLog(@"%@",notification.name);

NSLog(@"%@",notification.object);

NSDateFormatter *fmt = [[NSDateFormatter alloc] init];

NSDate *date = [NSDate date];

fmt.dateFormat = @"MM-dd"; // @"yyyy-MM-dd HH:mm:ss"

NSString *time = [fmt stringFromDate:date];

//保存到数据库,更新首页聊天记录

NSString *receiveData = (NSString *)notification.object;

NSError *error = nil;

NSData *jsonData = [receiveData dataUsingEncoding:NSUTF8StringEncoding];

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];

NSString* msgType = [dict objectForKey:@"type"];

NSLog(@"msgtype is %@",msgType);

NSString* chatFrom = [dict objectForKey:@"from"];

NSString* chatTo = [dict objectForKey:@"to"];

NSString* msg = [dict objectForKey:@"msg"];

if (![msg isEqualToString:@""]) {

[self addMessageWithContent:msg type:MessageTypeOther];

[self.tableChat reloadData];

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:arrayMessagesFrame.count - 1 inSection:0];

[self.tableChat scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

}

}

}

- (NSString*)generateTimeStamp

{

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateStyle:NSDateFormatterMediumStyle];

[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];

[dateFormatter setDateFormat:@"yyyyMMddhhmmss"];

NSString *timerid = [dateFormatter stringFromDate:[NSDate date]];

return timerid;

}

- (void)didReceiveMemoryWarning

{

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

return [arrayMessagesFrame count];

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

return [arrayMessagesFrame[indexPath.row] cellHeight];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

static NSString *simpleTableIdentifier = @"MessageCell";

MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

if (cell == nil) {

cell = [[MessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];

}

// 设置数据

cell.messageFrame = [arrayMessagesFrame objectAtIndex:indexPath.row];

cell.contentView.backgroundColor = [UIColor clearColor];

return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

[tableView deselectRowAtIndexPath:indexPath animated:NO];

[self.messageField resignFirstResponder];

}

聊天界面.m文件

时间: 2024-11-04 03:34:52

聊天界面.m文件的相关文章

Android学习笔记(十二)——实战:制作一个聊天界面

//此系列博文是<第一行Android代码>的学习笔记,如有错漏,欢迎指正! 运用简单的布局知识,我们可以来尝试制作一个聊天界面. 一.制作 Nine-Patch 图片 : Nine-Patch图片是一种被特殊处理过的 png 图片,能够指定哪些区域可以被拉伸而哪些区域不可以.一般用来作为聊天信息的背景.在此我们先准备一张png图片.然后在 Android sdk 目录下有一个 tools 文件夹,在这个文件夹中找到 draw9patch.bat文件. 双击打开之后, 在导航栏点击 File→

Android开发学习之路--UI之简单聊天界面

学了很多的ui的知识,这里就来实现个聊天的界面,首先来实现个layout的xml,代码如下: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:lay

[iOS基础控件 - 6.9] 聊天界面Demo

A.需求 做出一个类似于QQ.微信的聊天界面 1.每个cell包含发送时间.发送人(头像).发送信息 2.使用对方头像放在左边,我方头像在右边 3.对方信息使用白色背景对话框,我方信息使用蓝色背景对话框 4.隐藏相同的发送时间 5.底部功能按钮:语音按钮.消息输入框.表情按钮.附加按钮 6.响应键盘事件,呼出键盘.隐藏键盘时对上述的视图作出上移操作 7.键盘的发送事件处理 B.实现点 1.底层视图搭建 上部分聊天信息框:UITableView 下部分功能区:UIButton 信息输入框使用无边框

android 仿QQ气泡聊天界面

1.现在的QQ,微信等一些APP的聊天界面都是气泡聊天界面,左边是接收到的消息,右边是发送的消息, 这个效果其实就是一个ListView在加载它的Item的时候,分别用了不同的布局xml文件. 2.效果图(其中的聊天信息框是采用了.9.png的图片): 3.对中间聊天的的listView进行说明: 左边Item的xml文件效果如下: 右边Item的xml文件效果如下: 4.在加载ListView当中重写getView()方法,通过判断消息传入类型,来使item加载哪一个xml文件: 自定义ada

亲身体验用Java写的仿qq聊天界面

Java开发工具有许多种,新手用记事本写Java程序,有些人用NetBean,jbuilder,高手用eclipse,下面介绍用eclipse开发qq聊天界面. 代码如下: package Myjava_QQ; import java.awt.*; import javax.swing.*; import Myjava_QQ.truess; import java.awt.event.*; import java.applet.*; import java.io.BufferedReader;

【3】QQ 聊天界面

1.说明 稍微修改了下QQ示例里面的聊天界面界面,然后把代码扣过来完成了QQ聊天界面部分,效果还可以. 2.代码部分 // QQTalk.h文件 #ifndef __QQ_TALK_H__ #define __QQ_TALK_H__ #include <DuiLib/DuiLibEnv.h> #include <DuiLib/UIlib.h> using namespace DuiLib; #define QQ_TALK_XML _T("chatbox.xml"

仿QQ聊天界面&lt;一&gt;

先上图: 首先需要两个模型: 1->数据模型 2->位置模型 数据模型代码如下: Message.h文件里: #import <Foundation/Foundation.h> typedef enum { MessagesTypeMe = 0 , //自己发的 MessagesTypeOther //别人发的 }MessagesType; @interface Messages : NSObject /** * 聊天内容 */ @property (nonatomic ,copy

QQ聊天界面的输入法顶起界面底部输入框效果的实现

转载请注明:http://www.cnblogs.com/frank-zouxu/p/4127115.html 今天在公司做项目的时候遇到一个需求:需要做一个界面,效果类似QQ聊天界面,如图1,当我们点击内容输入框准备输入内容的时候,底部的表情框的那一栏会被输入法的软键盘给顶起来,默认状态下,输入法会覆盖掉我们的表情输入框.起初,百思不得解的我费尽了心思,未果,偶然看到此篇博客http://blog.csdn.net/twoicewoo/article/details/7384398.其实,欲达

简单模仿QQ聊天界面

首先看一下最终的效果,显示了消息时间,用户昵称,用户头像. 大致实现方法: 用最简单的ListView显示消息内容. 不同的用户使用不同的消息布局文件,例子有2个用户"Tony","Hill". 代码文件清单: 主布局文件activity_main.xml: 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools=&