简单聊天界面

1.在Main.storyboard中创建控制器和控件,添加约束,设置TextField 如图:

简单聊天界面_第1张图片

简单聊天界面_第2张图片

2.为TableView在控制器上添加delegate、datasource,为textField添加delegate

简单聊天界面_第3张图片            

3.在ViewController.m中添加代码

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *layoutConstraint;//UIView的底部约束,随着键盘弹出或者收缩而改变

@property (nonatomic,strong) NSMutableArray *msgArray;//保存输入的字符串

@end
@implementation ViewController

//对可变数组进行懒加载
-(NSMutableArray *)msgArray{
    if (!_msgArray) {
        _msgArray = [NSMutableArray array];
    }
    return _msgArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
//添加通知,监控键盘的变化
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

-(void)keyboardChange:(NSNotification *)notification{
    NSLog(@"%@",notification.userInfo);
    
    CGRect keyFrame = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];//获取键盘的Frame
    
    CGFloat keyFrameY = keyFrame.origin.y;//获取键盘的坐标Y
    
    self.layoutConstraint.constant = [UIScreen mainScreen].bounds.size.height - keyFrameY;//UIView底部的约束
}

#param mark - UITextfieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.msgArray addObject:textField.text];
    //发送之后,使输入框内容为空
    textField.text = nil;
    //加载表视图
    [self.tableView reloadData];
    
    NSIndexPath *index = [NSIndexPath indexPathForRow:(self.msgArray.count-1) inSection:0];
    //始终滚动出最新一行消息
    [self.tableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
    return YES;
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
//滚动表视图时,键盘收起
    [self.view endEditing:YES ];
}

#param mark - UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.msgArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MsgCell" forIndexPath:indexPath];
    
    cell.textLabel.text = [self.msgArray objectAtIndex:indexPath.row];
    
    return cell;
}



你可能感兴趣的:(iOS开发小结)