初始化TableView
- (UITableView *)chatListTB{
if (!_chatListTB) {
_chatListTB = [[UITableView alloc] initWithFrame:CGRectMake(0,0, ScreenWidth, ScreenHeight - BottomViewHeight - kBottomSafeHeight - kNAVBAR_HEIGHT)];
_chatListTB.backgroundColor = RGBA(235, 234, 229, 1);
_chatListTB.dataSource = self ;
_chatListTB.delegate = self ;
_chatListTB.tableFooterView = [[UIView alloc]init];
_chatListTB.separatorStyle = UITableViewCellSeparatorStyleNone ;
_chatListTB.estimatedRowHeight = 400;
_chatListTB.estimatedSectionHeaderHeight = 0;
_chatListTB.estimatedSectionFooterHeight = 0;
[_chatListTB registerClass:[DGEnterpriseChatListCell class] forCellReuseIdentifier:@"DGEnterpriseChatListCell"];
[_chatListTB addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenKeyBoard)]];
_chatListTB.showsVerticalScrollIndicator = NO ;
self.view.backgroundColor = RGBA(246, 246, 246, 1);
}
return _chatListTB;
}
初始化输入框
- (void)initBottomView{
//输入框背景
UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight - BottomViewHeight - kBottomSafeHeight - kNAVBAR_HEIGHT, ScreenWidth, BottomViewHeight)];
bgView.tag = 100;
bgView.backgroundColor = RGBA(246, 246, 246, 1);
bgView.layer.masksToBounds = YES;
[self.view addSubview:bgView];
self.bgView = bgView;
//输入框
UITextView *textView = [[UITextView alloc] init];
textView.layer.borderColor = [RGBA(233, 233, 233, 1) CGColor];
textView.layer.borderWidth = 0.5 ;
textView.layer.cornerRadius = 2 ;
textView.layer.masksToBounds = YES ;
textView.delegate = self;
textView.tag = 101;
textView.returnKeyType = UIReturnKeySend;
textView.font = FontSystemSize(16);
[bgView addSubview:textView];
self.chatTextView = textView ;
[textView mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerY.mas_equalTo(bgView.mas_centerY);
make.left.mas_equalTo(16);
make.right.mas_equalTo(-16);
make.height.mas_equalTo(36);
}];
}
监听键盘事件
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chatkeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chatkeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
弹出键盘
-(void)chatkeyboardWillShow:(NSNotification *)aNotification{
CGRect keyboardFrame = [aNotification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat keyboardY = keyboardFrame.origin.y;
CGFloat duration = [aNotification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[UIView animateWithDuration:duration delay:0 options:[aNotification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue] animations:^{
self.bgView.frame = CGRectMake(0, keyboardY - self.bgView.height - kNAVBAR_HEIGHT, ScreenWidth, self.bgView.height);
self.isScrollToBottom = YES ;
[self changeTableViewFrame:self.bgView.frame.origin.y];
} completion:nil];
}
收起键盘
- (void)chatkeyboardWillHide:(NSNotification *)aNotification{
[UIView animateWithDuration:1 animations:^{
self.bgView.frame = CGRectMake(0, ScreenHeight - BottomViewHeight - kBottomSafeHeight - kNAVBAR_HEIGHT, ScreenWidth, BottomViewHeight);
[self changeTableViewFrame:self.bgView.frame.origin.y];
}];
}
改变TableView的Frame
//改变tableview的frame
- (void)changeTableViewFrame:(CGFloat)minY{
if (self.chatMessageArray.count > 0) {
NSIndexPath *lastIndex = [NSIndexPath indexPathForRow:self.chatMessageArray.count -1 inSection:0];
CGRect rect = [self.chatListTB rectForRowAtIndexPath:lastIndex];
CGFloat lastMaxY = rect.origin.y + rect.size.height ;
NSLog(@"lastMaxY = %f,minY = %f",lastMaxY,minY);
//如果最后一个cell的最大值大于tableview的高度
if (lastMaxY <= self.chatListTB.frame.size.height) {
if (lastMaxY >= minY) {
self.chatListTB.y = minY - lastMaxY;
}else{
self.chatListTB.y = 0 ;
}
}else{
self.chatListTB.y += minY - self.chatListTB.maxY;
}
}
if (self.isScrollToBottom == YES) {
[self scrollToBootom];
self.isScrollToBottom = NO ;
}
}
消息滚动到最后一行
- (void)scrollToBootom{
dispatch_async(dispatch_get_main_queue(), ^{//回到主线程滚动
if (self.chatMessageArray.count > 0) {
[self.chatListTB scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:MAX(0, self.chatMessageArray.count - 1) inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
if (self.chatListTB.contentSize.height -self.chatListTB.bounds.size.height > 0) {//解决不满屏滚动的问题
[self.chatListTB setContentOffset:CGPointMake(0, self.chatListTB.contentSize.height -self.chatListTB.bounds.size.height) animated:YES];
}
}
});
}
主线程改变Frame
dispatch_async(dispatch_get_main_queue(), ^{
[self changeTableViewFrame:self.bgView.frame.origin.y];
});
五分钟内不展示时间
if (indexPath.row == 0) {//第一条展示时间
messageModel.showMessageTime = YES ;
}else{
DGEnterpriseChatMessageModel *preModel = self.chatMessageArray[indexPath.row - 1];
BOOL inFiveMinutes = [self isFiveMinutesWithTheBeginTime:preModel.createTime withEndTime:messageModel.createTime];
if (inFiveMinutes == YES) {//5分钟内不展示时间
messageModel.showMessageTime = NO ;
}else{
messageModel.showMessageTime = YES ;
}
}
对比两个时间戳
- (BOOL)isFiveMinutesWithTheBeginTime:(long long)beginTime withEndTime:(long long)endTime{
NSTimeInterval timer1 = beginTime / 1000.0;
NSTimeInterval timer2 = endTime / 1000.0;
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
NSDate* date = [NSDate dateWithTimeIntervalSince1970:timer1];
NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:timer2];
// 日历对象(方便比较两个日期之间的差距)
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit unit =NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *cmps = [calendar components:unit fromDate:date toDate:date2 options:0];
// 获得某个时间的年月日时分秒
// NSLog(@"差值%ld天,%ld小时%ld分%ld秒",cmps.day ,cmps.hour, cmps.minute,cmps.second);
if (cmps.day == 0 && cmps.hour == 0 && cmps.minute < 5 ) {
// NSLog(@"同一天并且是5分钟内的消息");
return YES;
}else{
// NSLog(@"不是5分钟内的消息");
return NO;
}
}
时间显示内容
-(NSString *)getDateDisplayString:(long long) miliSeconds{
NSTimeInterval tempMilli = miliSeconds;
NSTimeInterval seconds = tempMilli/1000.0;
NSDate *myDate = [NSDate dateWithTimeIntervalSince1970:seconds];
NSCalendar *calendar = [ NSCalendar currentCalendar ];
int unit = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear ;
NSDateComponents *nowCmps = [calendar components:unit fromDate:[ NSDate date ]];
NSDateComponents *myCmps = [calendar components:unit fromDate:myDate];
NSDateFormatter *dateFmt = [[NSDateFormatter alloc ] init ];
//2. 指定日历对象,要去取日期对象的那些部分.
NSDateComponents *comp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday fromDate:myDate];
if (nowCmps.year != myCmps.year) {
dateFmt.dateFormat = @"yyyy-MM-dd HH:mm";
} else {
if (nowCmps.day==myCmps.day) {
dateFmt.dateFormat = @"HH:mm";
} else if((nowCmps.day-myCmps.day)==1) {
dateFmt.dateFormat = @"昨天 HH:mm";
} else {
if ((nowCmps.day-myCmps.day) <=7) {
switch (comp.weekday) {
case 1:
dateFmt.dateFormat = @"星期日 HH:mm";
break;
case 2:
dateFmt.dateFormat = @"星期一 HH:mm";
break;
case 3:
dateFmt.dateFormat = @"星期二 HH:mm";
break;
case 4:
dateFmt.dateFormat = @"星期三 HH:mm";
break;
case 5:
dateFmt.dateFormat = @"星期四 HH:mm";
break;
case 6:
dateFmt.dateFormat = @"星期五 HH:mm";
break;
case 7:
dateFmt.dateFormat = @"星期六 HH:mm";
break;
default:
break;
}
}else {
dateFmt.dateFormat = @"MM-dd HH:mm";
}
}
}
return [dateFmt stringFromDate:myDate];
}
注意点:
- 需关闭全局键盘处理时间,如[IQKeyboardManager sharedManager].enableAutoToolbar = NO;
- 请求完数据之后,回到主线程刷新UI界面,不然无法滚动到最后一行