用UITableView模仿聊天界面(短信、微信、qq等),无网络和数据,仅仅模仿界面。
1、新建一个single view工程
2、编写viewcontroller
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>{
UITableView *_tableView;
NSMutableArray *_dataArray;//存放TableView的数据
UIView *_chatView;//放置底部的输入框和发送按钮
UITextField *_chatField;//输入框
}
@end
ViewController.m
在viewDidLoad方法中先初始化tableView和dataArray
//初始化数据数组
_dataArray = [[NSMutableArray alloc] init];
//初始化表格
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 420) style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;
[_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
[self.view addSubview:_tableView];
[_tableView release];
然后设置底部的输入框和发送按钮,将两者放在一个view上边
//设置聊天view
_chatView = [[UIView alloc] initWithFrame:CGRectMake(0, 460-40, 320, 40)];
_chatView.backgroundColor = [UIColor grayColor];
[self.view addSubview:_chatView];
[_chatView release];
//聊天field
_chatField = [[UITextField alloc] initWithFrame:CGRectMake(10, 5, 260, 30)];
_chatField.borderStyle = UITextBorderStyleRoundedRect;
_chatField.delegate = self;
[_chatView addSubview:_chatField];
[_chatField release];
//发送按钮
UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
sendBtn.frame = CGRectMake(280, 5, 35, 30);
[sendBtn addTarget:self action:@selector(sendText) forControlEvents:UIControlEventTouchUpInside];
[_chatView addSubview:sendBtn];
最后设置键盘的监听事件
//监听键盘事件
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];//object是指监听那个对象,空值所有都监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
实现两个监听方法
- (void)keyboardWillShow:(NSNotification *)noti
{
/************设置动画***************/
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.25];
//获取键盘宽高
CGSize size = [[noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
_chatView.frame = CGRectMake(0, 420-size.height, 320, 40);
_tableView.frame = CGRectMake(0, 0, 320, 420-size.height);
//提交动画,开始执行,注意代码位置
[UIView commitAnimations];
/*********************************/
}
- (void)keyboardWillHide:(NSNotification *)noti
{
// /************设置动画***************/
// [UIView beginAnimations:nil context:nil];
// [UIView setAnimationDuration:0.25];
_tableView.frame = CGRectMake(0, 0, 320, 420);
_chatView.frame = CGRectMake(0, 420, 320, 40);
// //提交动画,开始执行,注意代码位置
// [UIView commitAnimations];
/*********************************/
}
实现发送按钮的发送文本事件
- (void)sendText
{
if (_chatField.text == nil || [_chatField.text isEqualToString:@""]) {
return;
}
ChatItem *item = [[ChatItem alloc] init];
item.content = _chatField.text;
item.isSelf = YES;
[_dataArray addObject:item];
_chatField.text = @"";
//创建indexPath
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(_dataArray.count-1) inSection:0];
[_tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationBottom];
[_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
//自动回复
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(autoSpeak) userInfo:nil repeats:NO];
}
自动回复
- (void)autoSpeak
{
NSArray *array = [NSArray arrayWithObjects:@"呵呵", @"嘿嘿", @"哈哈", @"嘻嘻", @"恩恩", @"去洗澡", @"好的", nil];
ChatItem *item = [[ChatItem alloc] init];
item.content = [array objectAtIndex:arc4random()%array.count];
item.isSelf = NO;
[_dataArray addObject:item];
[item release];
//创建indexPath
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(_dataArray.count-1) inSection:0];
[_tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationBottom];
[_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
剩下的就是设置tableview的cell了
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ChatCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
if (cell == nil) {
cell = [[[ChatCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ID"] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
ChatItem *item = [_dataArray objectAtIndex:indexPath.row];
CGSize size = [item.content sizeWithFont:[UIFont systemFontOfSize:18] constrainedToSize:CGSizeMake(300, 100) lineBreakMode:UILineBreakModeCharacterWrap];
if (item.isSelf) {
cell.rightBubble.hidden = NO;
cell.leftBubble.hidden = YES;
cell.rightLabel.frame = CGRectMake(cell.rightLabel.frame.origin.x, cell.rightLabel.frame.origin.y, size.width, size.height);
cell.rightBubble.frame = CGRectMake(320-10-25-size.width, 5, 25+size.width, 20+size.height);
cell.rightLabel.text = item.content;
} else {
cell.rightBubble.hidden = YES;
cell.leftBubble.hidden = NO;
cell.leftLabel.text = item.content;
cell.leftLabel.frame = CGRectMake(cell.leftLabel.frame.origin.x, cell.leftLabel.frame.origin.y, size.width, size.height);
cell.leftBubble.frame = CGRectMake(cell.leftBubble.frame.origin.x, cell.leftBubble.frame.origin.y, size.width+25, size.height+20);
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
ChatItem *item = [_dataArray objectAtIndex:indexPath.row];
CGSize size = [item.content sizeWithFont:[UIFont systemFontOfSize:18] constrainedToSize:CGSizeMake(300, 100) lineBreakMode:UILineBreakModeCharacterWrap];
return size.height+20+10;
}
还有一个键盘的return事件
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[_chatField resignFirstResponder];
return YES;
}
自定义的cell:
ChatCell.h和ChatCell.m文件
#import <UIKit/UIKit.h>
@interface ChatCell : UITableViewCell
@property (nonatomic, retain) UIImageView *leftBubble;
@property (nonatomic, retain) UIImageView *rightBubble;
@property (nonatomic, retain) UILabel *leftLabel;
@property (nonatomic, retain) UILabel *rightLabel;
@end
#import "ChatCell.h"
@implementation ChatCell
@synthesize leftLabel = _leftLabel, rightLabel = _rightLabel, leftBubble = _leftBubble, rightBubble = _rightBubble;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
UIImage *leftImg = [UIImage imageNamed:@"ReceiverTextNodeBkg.png"];
UIImage *rightImg = [UIImage imageNamed:@"SenderTextNodeBkg.png"];
//设置图片拉伸
leftImg = [leftImg stretchableImageWithLeftCapWidth:30 topCapHeight:35];
rightImg = [rightImg stretchableImageWithLeftCapWidth:30 topCapHeight:35];
//设置左边气泡
self.leftBubble = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, 66, 54)];
self.leftBubble.image = leftImg;
[self.contentView addSubview:self.leftBubble];
//设置右边气泡
self.rightBubble = [[UIImageView alloc] initWithFrame:CGRectMake(320-10-66, 5, 66, 54)];
self.rightBubble.image = rightImg;
[self.contentView addSubview:self.rightBubble];
//设置左边label
self.leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, 0, 0)];
self.leftLabel.backgroundColor = [UIColor clearColor];
self.leftLabel.numberOfLines = 0;
self.leftLabel.lineBreakMode = UILineBreakModeCharacterWrap;
self.leftLabel.font = [UIFont systemFontOfSize:14];
[self.leftBubble addSubview:self.leftLabel];
[self.leftLabel release];
//设置右边label
self.rightLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, 0, 0)];
self.rightLabel.backgroundColor = [UIColor clearColor];
self.rightLabel.numberOfLines = 0;
self.rightLabel.lineBreakMode = UILineBreakModeCharacterWrap;
self.rightLabel.font = [UIFont systemFontOfSize:14];
[self.rightBubble addSubview:self.rightLabel];
[self.rightLabel release];
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
}
- (void)dealloc
{
self.leftLabel = nil;
self.rightLabel = nil;
self.leftBubble = nil;
self.rightBubble = nil;
[super dealloc];
}
@end
最后是一个model
@interface ChatItem : NSObject
@property (nonatomic, copy) NSString *content;
@property (nonatomic, assign) BOOL isSelf;
@end
@implementation ChatItem
@synthesize isSelf = _isSelf, content = _content;
- (void)dealloc
{
self.content = nil;
[super dealloc];
}
@end