简单聊天界面

来源:互联网 发布:密码框键入数据是 编辑:程序博客网 时间:2024/06/02 06:38

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



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

            

3.在ViewController.m中添加代码

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>@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;}



0 0
原创粉丝点击