Model层
消息实体
//
// Message.h
// QQ聊天界面
//
// Created by Tony on 15/9/29.
// Copyright (c) 2015年 Tony. All rights reserved.
//
#import <Foundation/Foundation.h>
//枚举
typedef enum {
MessageTypeMe=0,
MessageTypeOther=1
}MessageType;
@interface Message : NSObject
@property(nonatomic,copy)NSString *text;
@property(nonatomic,copy)NSString *time;
@property(nonatomic)MessageType type;
-(instancetype)initWithDict:(NSDictionary*)dict;
+(instancetype)messageWithDict:(NSDictionary*)dict;
@end
//
// Message.m
// QQ聊天界面
//
// Created by Tony on 15/9/29.
// Copyright (c) 2015年 Tony. All rights reserved.
//
#import "Message.h"
@implementation Message
-(instancetype)initWithDict:(NSDictionary*)dict
{
if (self=[super init]) {
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
+(instancetype)messageWithDict:(NSDictionary*)dict
{
return [[self alloc] initWithDict:dict];
}
@end
消息frame实体
//
// MessageFrame.h
// QQ聊天界面
//
// Created by Tony on 15/9/29.
// Copyright (c) 2015年 Tony. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Message.h"
#import <CoreGraphics/CoreGraphics.h>
#import "NSString+NSStringExt.h"
#define textFont [UIFont systemFontOfSize:13]
@interface MessageFrame : NSObject
//引用数据模型
@property(nonatomic,strong)Message *message;
//时间
@property(nonatomic,assign,readonly)CGRect timeFrame;
//正文
@property(nonatomic,assign,readonly)CGRect textFrame;
//头像
@property(nonatomic,assign,readonly)CGRect iconFrame;
//行高
@property(nonatomic,assign,readonly)CGFloat rowHeigh;
@end
//
// MessageFrame.m
// QQ聊天界面
//
// Created by Tony on 15/9/29.
// Copyright (c) 2015年 Tony. All rights reserved.
//
#import "MessageFrame.h"
//导用UIKit/UIKit.h用于取屏幕宽度
#import <UIKit/UIKit.h>
@implementation MessageFrame
//重写set方法
- (void)setMessage:(Message *)message
{
_message=message;
//获取屏幕宽度
CGFloat screenW=[UIScreen mainScreen].bounds.size.width;
//设置一个统一的间距
CGFloat margin=5;
//计算每个字控件的frame
//时间
CGFloat timeX=0;
CGFloat timeY=0;
CGFloat timeW=screenW;
CGFloat timeH=self.message.time.length>0?15:0;
_timeFrame=CGRectMake(timeX, timeY, timeW, timeH);
//头像
CGFloat iconW=30;
CGFloat iconH=30;
CGFloat iconY=CGRectGetMaxY(_timeFrame)+margin;
CGFloat iconX=message.type==MessageTypeOther?margin:(screenW-margin-iconW);
_iconFrame=CGRectMake(iconX, iconY, iconW, iconH);
//正文
//1.先计算正文的大小
CGSize textSize=[self.message.text sizeOfTextWithMaxSize:CGSizeMake(200, MAXFLOAT) font:textFont];
//给尺寸时加多40的边距,用于展示数据
CGFloat textW=textSize.width+40;
CGFloat textH=textSize.height+30;
//2.再计算x.y
CGFloat textY=iconY;
CGFloat textX=self.message.type==MessageTypeOther?(CGRectGetMaxX(_iconFrame)+margin):(screenW-margin*2-iconW-textW);
NSLog(@"mesagetype is : %d,",self.message.type);
_textFrame=CGRectMake(textX, textY, textW, textH);
//计算高度,传入两个值,返回最大值MAX(A,B)
CGFloat rowHeight=MAX(CGRectGetMaxY(_textFrame), CGRectGetMaxY(_iconFrame));
_rowHeigh=rowHeight+margin;
}
@end
//
// MessageCell.h
// QQ聊天界面
//
// Created by Tony on 15/9/29.
// Copyright (c) 2015年 Tony. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "MessageFrame.h"
@interface MessageCell : UITableViewCell
+(instancetype)messageCellWithTableView:(UITableView*)tableView;
@property(nonatomic,strong)MessageFrame *messageFrame;
@end
//
// MessageCell.m
// QQ聊天界面
//
// Created by Tony on 15/9/29.
// Copyright (c) 2015年 Tony. All rights reserved.
//
#import "MessageCell.h"
#import "Message.h"
@interface MessageCell ()
@property(nonatomic,weak)UILabel *lblTime;
@property(nonatomic,weak)UIImageView *imgViewIcon;
@property(nonatomic,weak)UIButton *btnText;
@end
@implementation MessageCell
+(instancetype)messageCellWithTableView:(UITableView*)tableView
{
static NSString *ID=@"messageCell";
MessageCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
if (cell==nil) {
cell=[[MessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
}
return cell;
}
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
if (self=[super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
//时间
UILabel *lblTime=[[UILabel alloc] init];
[self.contentView addSubview:lblTime];
lblTime.textAlignment=NSTextAlignmentCenter;
lblTime.font=[UIFont systemFontOfSize:12];
lblTime.textColor=[UIColor grayColor];
self.lblTime=lblTime;
//头像
UIImageView *imgViewIcon=[[UIImageView alloc] init];
[self.contentView addSubview:imgViewIcon];
self.imgViewIcon=imgViewIcon;
//正文
UIButton *btnText= [[UIButton alloc] init];
[self.contentView addSubview:btnText];
btnText.titleLabel.font=[UIFont systemFontOfSize:13];
[btnText setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
btnText.titleLabel.numberOfLines=0;
//设置按钮的内边距
btnText.contentEdgeInsets=UIEdgeInsetsMake(15, 15, 15, 20);
[self.contentView addSubview:btnText];
self.btnText=btnText;
}
self.backgroundColor=[UIColor clearColor];
return self;
}
- (void)awakeFromNib {
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
//重写self.messageFrame的set方法
- (void)setMessageFrame:(MessageFrame *)messageFrame
{
_messageFrame=messageFrame;
//设置数据
[self settingData];
}
-(void)settingData
{
//设置时间
self.lblTime.text=self.messageFrame.message.time;
self.lblTime.frame=self.messageFrame.timeFrame;
//设置头
//根据消息类型,判断应该使用哪张图片
NSString *iconImg=self.messageFrame.message.type==MessageTypeMe?@"me":@"other";
self.imgViewIcon.image=[UIImage imageNamed:iconImg];
self.imgViewIcon.frame=self.messageFrame.iconFrame;
//设计正文
[self.btnText setTitle:self.messageFrame.message.text forState:UIControlStateNormal];
self.btnText.frame=self.messageFrame.textFrame;
NSString *imgNor,*imgHighlighted;
if (self.messageFrame.message.type==MessageTypeMe) {
imgNor=@"send_other";
imgHighlighted=@"send_other_select";
[self.btnText setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
}else
{
imgNor=@"send_me";
imgHighlighted=@"send_me_select";
[self.btnText setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}
//把图片平铺拉升 类似anddroid的.9.png格式
UIImage *imgeNor=[UIImage imageNamed:imgNor];
imgeNor=[imgeNor stretchableImageWithLeftCapWidth:imgeNor.size.width*0.5 topCapHeight:imgeNor.size.height*0.5];
UIImage *imgHightlighted=[UIImage imageNamed:imgHighlighted];
imgHightlighted=[imgHightlighted stretchableImageWithLeftCapWidth:imgHightlighted.size.width*0.5 topCapHeight:imgHightlighted.size.height*0.5];
//设置背景图片
[self.btnText setBackgroundImage:imgeNor forState:UIControlStateNormal];
[self.btnText setBackgroundImage: imgHightlighted forState:UIControlStateHighlighted];
}
@end
//
// ViewController.m
// QQ聊天界面
//
// Created by Tony on 15/9/29.
// Copyright (c) 2015年 Tony. All rights reserved.
//
#import "ViewController.h"
#import "Message.h"
#import "MessageFrame.h"
#import "MessageCell.h"
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *txtInput;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *messageFrames;
@end
@implementation ViewController
//懒加载数据
- (NSMutableArray *)messageFrames
{
if (_messageFrames==nil) {
NSString *path=[[NSBundle mainBundle] pathForResource:@"message.plist" ofType:nil];
NSArray *arrayDict=[NSArray arrayWithContentsOfFile:path];
NSMutableArray *arrayModels=[NSMutableArray array];
for (NSDictionary *dict in arrayDict) {
Message *model=[Message messageWithDict:dict];
//取到上一个模型
MessageFrame *lastModel=(MessageFrame*)[arrayModels lastObject];
if ([model.time isEqualToString:lastModel.message.time]) {
model.time=@"";
}
MessageFrame *modelFrame=[[MessageFrame alloc] init];
modelFrame.message=model;
[arrayModels addObject:modelFrame];
}
_messageFrames=arrayModels;
}
return _messageFrames;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
self.tableView.backgroundColor=[UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1.0];
self.tableView.allowsSelection=NO;
//ios6以下时使用,光标往右边移5像素
// UIView *leftVw=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 1)];
// leftVw.backgroundColor=[UIColor redColor];
// self.txtInput.leftView=leftVw;
// self.txtInput.leftViewMode=UITextFieldViewModeAlways;
//监听键盘的弹出事件
//1.创建一个NSNotificationCenter对象
NSNotificationCenter *center=[NSNotificationCenter defaultCenter];
//监听键盘的弹出通知
[center addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
self.txtInput.returnKeyType=UIReturnKeySend;
self.txtInput.delegate=self;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSString *text= self.txtInput.text;
[self sendMessage:text withType:MessageTypeMe];
[self sendMessage:@"不认识" withType:MessageTypeOther];
[self.view endEditing:YES];
return YES;
}
-(void)sendMessage:(NSString*)text withType:(MessageType)typett
{
Message *model=[[Message alloc] init];
model.text=text;
//取当前系统时间
NSDate *nowDate=[NSDate date];
//创建日期格式化器
NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
formatter.dateFormat=@"今天 HH:mm";
model.time=[formatter stringFromDate:nowDate];
model.type=typett;
//判断是否与上一条时间相等,设置是否隐藏时间
MessageFrame *lastMessage=[self.messageFrames lastObject];
if ([model.time isEqualToString:lastMessage.message.time]) {
model.time=@"";
}
//创建一个新的frame模型
MessageFrame *modelFrame=[[MessageFrame alloc] init];
modelFrame.message=model;
//添加到数组中
[self.messageFrames addObject:modelFrame];
[self.tableView reloadData];
//弹出的事,把table滚动到最后
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messageFrames.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
//拖动tableView时让键盘缩回去,结束键盘
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
[self.view endEditing:YES];
}
-(void)keyboardWillChangeFrame:(NSNotification*)noteInfo
{
// NSLog(@"通知名字:%@",noteInfo.name);
// NSLog(@"通知发布者:%@",noteInfo.object);
// NSLog(@"通知的内容:%@",noteInfo.userInfo);
//
//1.获键盘的Y值
CGRect rectEnd=[noteInfo.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat keyboardY=rectEnd.origin.y;
CGFloat tranformValue=keyboardY-self.view.frame.size.height;
[UIView animateWithDuration:0.5 animations:^{
self.view.transform=CGAffineTransformMakeTranslation(0, tranformValue);
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.messageFrames.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//1.取模型
MessageFrame *model=self.messageFrames [indexPath.row];
//2.创建单元格
MessageCell *cell=[MessageCell messageCellWithTableView:tableView];
//给把模型给单元格对像
cell.messageFrame=model;
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
MessageFrame *model=self.messageFrames[indexPath.row];
return model.rowHeigh;
}
-(BOOL)prefersStatusBarHidden
{
return YES;
}
@end
//
// NSString+NSStringExt.h
// QQ聊天界面
//
// Created by Tony on 15/9/29.
// Copyright (c) 2015年 Tony. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface NSString (NSStringExt)
//对像方法
-(CGSize)sizeOfTextWithMaxSize:(CGSize)maxSize font:(UIFont*)font;
//类方法
+(CGSize)sizeWithText:(NSString*)text maxSize:(CGSize)maxSize font:(UIFont*)font;
@end
//
// NSString+NSStringExt.m
// QQ聊天界面
//
// Created by Tony on 15/9/29.
// Copyright (c) 2015年 Tony. All rights reserved.
//
#import "NSString+NSStringExt.h"
@implementation NSString (NSStringExt)
//对像方法
-(CGSize)sizeOfTextWithMaxSize:(CGSize)maxSize font:(UIFont*)font
{
NSDictionary *attr=@{NSFontAttributeName:font};
return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attr context:nil].size;
}
//类方法
+(CGSize)sizeWithText:(NSString*)text maxSize:(CGSize)maxSize font:(UIFont*)font
{
return [text sizeOfTextWithMaxSize:maxSize font:font];
}
@end