气泡聊天

import "ViewController.h"

@interface ViewController ()
{
    //用盛放说话的内容
    NSMutableArray *_dataArray;
    //底部的视图
    UIView *_bottomView;
    //输入框
    UITextField *_textField;
    //判断是谁说
    BOOL _who;
}
@property (retain, nonatomic) IBOutlet UITableView *tableView;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    _dataArray = [[NSMutableArray alloc] init];
    [self createBottomView];
    //separatorStyle 设置cell分割线的样式
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //UIScrollViewKeyboardDismissModeOnDrag 当拖动的时候让键盘隐藏
    _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
}

#pragma mark - 创建底部的视图
- (void)createBottomView
{
    //背景图,输入框,按钮 都放在一个view之上,当键盘弹出的时候,改变view的frame即可
    //创建一个视图
    _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 480-44, 320, 44)];
    [self.view addSubview:_bottomView];
    //添加背景图
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    imgView.image = [UIImage imageNamed:@"bg"];
    [_bottomView addSubview:imgView];
    [imgView release];
    //添加输入框
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(7, 7, 253, 30)];
    _textField.borderStyle = UITextBorderStyleRoundedRect;
    //设置输入框的代理
    _textField.delegate = self;
    [_bottomView addSubview:_textField];
    //添加发送按钮
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(260, 0, 60, 44);
    [btn setTitle:@"发送" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:btn];
}

#pragma mark - 发送按钮点击方法
- (void)sendMessage
{
    if ([_textField.text isEqualToString:@""])
    {
        //当内容为空的时候,不发送
        return;
    }
    //说的内容:谁、时间、说的话都在一个视图之上,当你需要显示内容的时候,让cell  addSubview
    //当是YES:我,当是NO:静静
    _who = !_who;
    //1.获取由谁说
    //如果条件为真,执行结果1;如果条件为假,执行结果2
    //三目运算符    条件?结果1:结果2
    NSString *name = _who?@"我":@"静静";
    
    //2.获取说的时间
    //获取当前时间
    NSDate *date = [NSDate date];
    //时间格式化器
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //设置时间格式
    formatter.dateFormat = @"MM-dd HH:mm:ss";
    //把时间转化成字符串
    NSString *time = [formatter stringFromDate:date];

    //3.拼接所说的内容
    NSString *message = [NSString stringWithFormat:@"%@在%@说:\n %@",name,time,_textField.text];

    //4.获取盛放内容的视图
    UIView *view = [self createViewWithMessage:message];
    [_dataArray addObject:view];

    //5.刷新表
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_dataArray.count-1 inSection:0];
    [_tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    //当有新消息时,显示最后一行
    //根据表的索引,移动到指定的位置
    //atScrollPosition 要移动的位置
    //UITableViewScrollPositionBottom 移动到底部
    [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

    //清空输入框的内容
    _textField.text = @"";
}
//根据说的内容创建视图
- (UIView *)createViewWithMessage:(NSString *)message
{
    //获取文字内容宽高
    //参数1.文字的宽度200 和 高LONG_MAX
    //2.NSStringDrawingUsesLineFragmentOrigin根据行高计算文字的高度
    //3.attributes 文字的大小,和lab保持一致
    CGRect rect = [message boundingRectWithSize:CGSizeMake(200, LONG_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14]} context:nil];

    //获取文字的高度
    float height = rect.size.height;
    float width = rect.size.width;
    //根据谁谁判断x坐标
    float x = _who?self.view.frame.size.width-width-30:0;
    //1.创建view
    UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(x, 0, width+30, height+30)] autorelease];
    view.tag = 10;

    //2.添加气泡
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, width+20, height+20)];
    //根据谁说获取图片名字
    NSString *imgName = _who?@"bubbleSelf":@"bubble";
    UIImage *img = [UIImage imageNamed:imgName];
    //stretchableImage拉伸图片
    //LeftCapWidth距左边多少开始拉伸
    //topCapHeight距上面多少开始拉伸
    //img.size.width 获取图片的宽
    imgView.image = [img stretchableImageWithLeftCapWidth:img.size.width*0.5 topCapHeight:img.size.height*0.5];
    [view addSubview:imgView];
    [imgView release];

    //3.添加lab显示文字
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(15, 15, width, height)];
    //要比显示文字大小小一点
    lab.font = [UIFont systemFontOfSize:13];
    lab.numberOfLines = 0;
    lab.text = message;
    [view addSubview:lab];
    [lab release];

    return view;
}

#pragma mark - UITextFieldDelegate
//将要开始编辑的时候,键盘弹出,改变底部视图和表的位置
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    //添加动画  216
    [UIView animateWithDuration:0.25 animations:^{
    //让_bottomView上去
    _bottomView.frame = CGRectMake(0, 480-44-216, 320, 44);
    //让表上去
    _tableView.frame = CGRectMake(0, 0, 320, 480-44-216);
    }];

    return YES;
}
//将要结束编辑,键盘下去,底部视图和表也下去
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.25 animations:^{
    //视图下去,回到初始位置
    _bottomView.frame = CGRectMake(0, 480-44, 320, 44);
    //改变表的位置
    _tableView.frame = CGRectMake(0, 0, 320, 480-44);
    }];
    
    return YES;
}
//点击return让键盘隐藏,失去第一响应
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //resignFirstResponder失去第一响应
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - 表的数据源和代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    //先把添加的视图移除,防止重用
    UIView *view10 = [cell viewWithTag:10];
    [view10 removeFromSuperview];

    //显示要说的内容
    //从数组中获取要说的内容
    UIView *view = [_dataArray objectAtIndex:indexPath.row];
    [cell addSubview:view];

    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //根据view的高度设置单元格的高度
    UIView *view = [_dataArray objectAtIndex:indexPath.row];
    return view.frame.size.height;
}

- (void)dealloc {
    [_dataArray release];
    [_textField release];
    [_bottomView release];
    [_tableView release];
    [super dealloc];
}
@end

附. UITextField 的代理方法
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
NSLog(@"将要开始编辑");

    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSLog(@"已经开始编辑");
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    NSLog(@"将要结束编辑");

    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSLog(@"已经结束编辑");
}
//改变输入框内容的时候调用
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSLog(@"我要开始写啦");

    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSLog(@"点击了return");
    //键盘弹出:成为第一响应becomeFirstResponder
    //键盘隐藏:失去第一响应resignFirstResponder
    //点击return键让键盘隐藏
    [textField resignFirstResponder];

    return YES;
}

你可能感兴趣的:(气泡聊天)