-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathXHMessageTableViewController.m
More file actions
1283 lines (1062 loc) · 45.9 KB
/
XHMessageTableViewController.m
File metadata and controls
1283 lines (1062 loc) · 45.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// XHMessageTableViewController.m
// MessageDisplayExample
//
// Created by HUAJIE-1 on 14-4-24.
// Copyright (c) 2014年 曾宪华 开发团队(http://iyilunba.com ) 本人QQ:543413507 本人QQ群(142557668). All rights reserved.
//
#import "XHMessageTableViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
@interface XHMessageTableViewController ()
/**
* 判断是否用户手指滚动
*/
@property (nonatomic, assign) BOOL isUserScrolling;
/**
* 记录旧的textView contentSize Heigth
*/
@property (nonatomic, assign) CGFloat previousTextViewContentHeight;
/**
* 记录键盘的高度,为了适配iPad和iPhone
*/
@property (nonatomic, assign) CGFloat keyboardViewHeight;
@property (nonatomic, assign, readwrite) XHInputViewType textViewInputViewType;
@property (nonatomic, weak, readwrite) XHMessageTableView *messageTableView;
@property (nonatomic, weak, readwrite) XHMessageInputView *messageInputView;
@property (nonatomic, weak, readwrite) XHShareMenuView *shareMenuView;
@property (nonatomic, weak, readwrite) XHEmotionManagerView *emotionManagerView;
@property (nonatomic, strong, readwrite) XHVoiceRecordHUD *voiceRecordHUD;
@property (nonatomic, strong) UIView *headerContainerView;
@property (nonatomic, strong) UIActivityIndicatorView *loadMoreActivityIndicatorView;
/**
* 管理本机的摄像和图片库的工具对象
*/
@property (nonatomic, strong) XHPhotographyHelper *photographyHelper;
/**
* 管理地理位置的工具对象
*/
@property (nonatomic, strong) XHLocationHelper *locationHelper;
/**
* 管理录音工具对象
*/
@property (nonatomic, strong) XHVoiceRecordHelper *voiceRecordHelper;
/**
* 判断是不是超出了录音最大时长
*/
@property (nonatomic) BOOL isMaxTimeStop;
#pragma mark - DataSource Change
/**
* 改变数据源需要的子线程
*
* @param queue 子线程执行完成的回调block
*/
- (void)exChangeMessageDataSourceQueue:(void (^)())queue;
/**
* 执行块代码在主线程
*
* @param queue 主线程执行完成回调block
*/
- (void)exMainQueue:(void (^)())queue;
#pragma mark - Previte Method
/**
* 判断是否允许滚动
*
* @return 返回判断结果
*/
- (BOOL)shouldAllowScroll;
#pragma mark - Life Cycle
/**
* 配置默认参数
*/
- (void)setup;
/**
* 初始化显示控件
*/
- (void)initilzer;
#pragma mark - RecorderPath Helper Method
/**
* 获取录音的路径
*
* @return 返回录音的路径
*/
- (NSString *)getRecorderPath;
#pragma mark - UITextView Helper Method
/**
* 获取某个UITextView对象的content高度
*
* @param textView 被获取的textView对象
*
* @return 返回高度
*/
- (CGFloat)getTextViewContentH:(UITextView *)textView;
#pragma mark - Layout Message Input View Helper Method
/**
* 动态改变TextView的高度
*
* @param textView 被改变的textView对象
*/
- (void)layoutAndAnimateMessageInputTextView:(UITextView *)textView;
#pragma mark - Scroll Message TableView Helper Method
/**
* 根据bottom的数值配置消息列表的内部布局变化
*
* @param bottom 底部的空缺高度
*/
- (void)setTableViewInsetsWithBottomValue:(CGFloat)bottom;
/**
* 根据底部高度获取UIEdgeInsets常量
*
* @param bottom 底部高度
*
* @return 返回UIEdgeInsets常量
*/
- (UIEdgeInsets)tableViewInsetsWithBottomValue:(CGFloat)bottom;
#pragma mark - Message Calculate Cell Height
/**
* 统一计算Cell的高度方法
*
* @param message 被计算目标消息对象
* @param indexPath 被计算目标消息所在的位置
*
* @return 返回计算的高度
*/
- (CGFloat)calculateCellHeightWithMessage:(id <XHMessageModel>)message atIndexPath:(NSIndexPath *)indexPath;
#pragma mark - Message Send helper Method
/**
* 根据文本开始发送文本消息
*
* @param text 目标文本
*/
- (void)didSendMessageWithText:(NSString *)text;
/**
* 根据图片开始发送图片消息
*
* @param photo 目标图片
*/
- (void)didSendMessageWithPhoto:(UIImage *)photo;
/**
* 根据视频的封面和视频的路径开始发送视频消息
*
* @param videoConverPhoto 目标视频的封面图
* @param videoPath 目标视频的路径
*/
- (void)didSendMessageWithVideoConverPhoto:(UIImage *)videoConverPhoto videoPath:(NSString *)videoPath;
/**
* 根据录音路径开始发送语音消息
*
* @param voicePath 目标语音路径
* @param voiceDuration 目标语音时长
*/
- (void)didSendMessageWithVoice:(NSString *)voicePath voiceDuration:(NSString*)voiceDuration;
/**
* 根据第三方gif表情路径开始发送表情消息
*
* @param emotionPath 目标gif表情路径
*/
- (void)didSendEmotionMessageWithEmotionPath:(NSString *)emotionPath;
/**
* 根据地理位置信息和地理经纬度开始发送地理位置消息
*
* @param geolcations 目标地理信息
* @param location 目标地理经纬度
*/
- (void)didSendGeolocationsMessageWithGeolocaltions:(NSString *)geolcations location:(CLLocation *)location;
#pragma mark - Voice Recording Helper Method
/**
* 开始录音
*/
- (void)startRecord;
/**
* 完成录音
*/
- (void)finishRecorded;
/**
* 想停止录音
*/
- (void)pauseRecord;
/**
* 继续录音
*/
- (void)resumeRecord;
/**
* 取消录音
*/
- (void)cancelRecord;
@end
@implementation XHMessageTableViewController
#pragma mark - DataSource Change
- (void)exChangeMessageDataSourceQueue:(void (^)())queue {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), queue);
}
- (void)exMainQueue:(void (^)())queue {
dispatch_async(dispatch_get_main_queue(), queue);
}
- (void)addMessage:(XHMessage *)addedMessage {
WEAKSELF
[self exChangeMessageDataSourceQueue:^{
NSMutableArray *messages = [NSMutableArray arrayWithArray:weakSelf.messages];
[messages addObject:addedMessage];
NSMutableArray *indexPaths = [NSMutableArray arrayWithCapacity:1];
[indexPaths addObject:[NSIndexPath indexPathForRow:messages.count - 1 inSection:0]];
[weakSelf exMainQueue:^{
weakSelf.messages = messages;
[weakSelf.messageTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
[weakSelf scrollToBottomAnimated:YES];
}];
}];
}
- (void)removeMessageAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row >= self.messages.count)
return;
[self.messages removeObjectAtIndex:indexPath.row];
NSMutableArray *indexPaths = [NSMutableArray arrayWithCapacity:1];
[indexPaths addObject:indexPath];
[self.messageTableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationBottom];
}
static CGPoint delayOffset = {0.0};
// http://stackoverflow.com/a/11602040 Keep UITableView static when inserting rows at the top
- (void)insertOldMessages:(NSArray *)oldMessages completion:(void (^)())completion {
WEAKSELF
[self exChangeMessageDataSourceQueue:^{
delayOffset = weakSelf.messageTableView.contentOffset;
NSMutableArray *indexPaths = [[NSMutableArray alloc] initWithCapacity:oldMessages.count];
NSMutableIndexSet *indexSets = [[NSMutableIndexSet alloc] init];
[oldMessages enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:idx inSection:0];
[indexPaths addObject:indexPath];
delayOffset.y += [weakSelf calculateCellHeightWithMessage:[oldMessages objectAtIndex:idx] atIndexPath:indexPath];
[indexSets addIndex:idx];
}];
NSMutableArray *messages = [[NSMutableArray alloc] initWithArray:weakSelf.messages];
[messages insertObjects:oldMessages atIndexes:indexSets];
[weakSelf exMainQueue:^{
[UIView setAnimationsEnabled:NO];
weakSelf.messageTableView.userInteractionEnabled = NO;
//[self.messageTableView beginUpdates];
weakSelf.messages = messages;
[weakSelf.messageTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
//[self.messageTableView endUpdates];
[UIView setAnimationsEnabled:YES];
[weakSelf.messageTableView setContentOffset:delayOffset animated:NO];
weakSelf.messageTableView.userInteractionEnabled = YES;
if (completion) {
completion();
}
}];
}];
}
- (void)insertOldMessages:(NSArray *)oldMessages {
[self insertOldMessages:oldMessages completion:nil];
}
#pragma mark - Propertys
- (NSMutableArray *)messages {
if (!_messages) {
_messages = [[NSMutableArray alloc] initWithCapacity:0];
}
return _messages;
}
- (UIView *)headerContainerView {
if (!_headerContainerView) {
_headerContainerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 44)];
_headerContainerView.backgroundColor = self.messageTableView.backgroundColor;
[_headerContainerView addSubview:self.loadMoreActivityIndicatorView];
}
return _headerContainerView;
}
- (UIActivityIndicatorView *)loadMoreActivityIndicatorView {
if (!_loadMoreActivityIndicatorView) {
_loadMoreActivityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
_loadMoreActivityIndicatorView.center = CGPointMake(CGRectGetWidth(_headerContainerView.bounds) / 2.0, CGRectGetHeight(_headerContainerView.bounds) / 2.0);
}
return _loadMoreActivityIndicatorView;
}
- (void)setLoadingMoreMessage:(BOOL)loadingMoreMessage {
_loadingMoreMessage = loadingMoreMessage;
if (loadingMoreMessage) {
[self.loadMoreActivityIndicatorView startAnimating];
} else {
[self.loadMoreActivityIndicatorView stopAnimating];
}
}
- (void)setLoadMoreActivityIndicatorViewStyle:(UIActivityIndicatorViewStyle)loadMoreActivityIndicatorViewStyle {
_loadMoreActivityIndicatorViewStyle = loadMoreActivityIndicatorViewStyle;
self.loadMoreActivityIndicatorView.activityIndicatorViewStyle = loadMoreActivityIndicatorViewStyle;
}
- (XHShareMenuView *)shareMenuView {
if (!_shareMenuView) {
XHShareMenuView *shareMenuView = [[XHShareMenuView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.bounds), CGRectGetWidth(self.view.bounds), self.keyboardViewHeight)];
shareMenuView.delegate = self;
shareMenuView.backgroundColor = [UIColor colorWithWhite:0.961 alpha:1.000];
shareMenuView.alpha = 0.0;
shareMenuView.shareMenuItems = self.shareMenuItems;
[self.view addSubview:shareMenuView];
_shareMenuView = shareMenuView;
}
[self.view bringSubviewToFront:_shareMenuView];
return _shareMenuView;
}
- (XHEmotionManagerView *)emotionManagerView {
if (!_emotionManagerView) {
XHEmotionManagerView *emotionManagerView = [[XHEmotionManagerView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.bounds), CGRectGetWidth(self.view.bounds), self.keyboardViewHeight)];
emotionManagerView.delegate = self;
emotionManagerView.dataSource = self;
emotionManagerView.backgroundColor = [UIColor colorWithWhite:0.961 alpha:1.000];
emotionManagerView.alpha = 0.0;
[self.view addSubview:emotionManagerView];
_emotionManagerView = emotionManagerView;
}
[self.view bringSubviewToFront:_emotionManagerView];
return _emotionManagerView;
}
- (XHVoiceRecordHUD *)voiceRecordHUD {
if (!_voiceRecordHUD) {
_voiceRecordHUD = [[XHVoiceRecordHUD alloc] initWithFrame:CGRectMake(0, 0, 140, 140)];
}
return _voiceRecordHUD;
}
- (XHPhotographyHelper *)photographyHelper {
if (!_photographyHelper) {
_photographyHelper = [[XHPhotographyHelper alloc] init];
}
return _photographyHelper;
}
- (XHLocationHelper *)locationHelper {
if (!_locationHelper) {
_locationHelper = [[XHLocationHelper alloc] init];
}
return _locationHelper;
}
- (XHVoiceRecordHelper *)voiceRecordHelper {
if (!_voiceRecordHelper) {
_isMaxTimeStop = NO;
WEAKSELF
_voiceRecordHelper = [[XHVoiceRecordHelper alloc] init];
_voiceRecordHelper.maxTimeStopRecorderCompletion = ^{
DLog(@"已经达到最大限制时间了,进入下一步的提示");
// Unselect and unhilight the hold down button, and set isMaxTimeStop to YES.
UIButton *holdDown = weakSelf.messageInputView.holdDownButton;
holdDown.selected = NO;
holdDown.highlighted = NO;
weakSelf.isMaxTimeStop = YES;
[weakSelf finishRecorded];
};
_voiceRecordHelper.peakPowerForChannel = ^(float peakPowerForChannel) {
weakSelf.voiceRecordHUD.peakPower = peakPowerForChannel;
};
_voiceRecordHelper.maxRecordTime = kVoiceRecorderTotalTime;
}
return _voiceRecordHelper;
}
#pragma mark - Messages View Controller
- (void)finishSendMessageWithBubbleMessageType:(XHBubbleMessageMediaType)mediaType {
switch (mediaType) {
case XHBubbleMessageMediaTypeText: {
[self.messageInputView.inputTextView setText:nil];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
self.messageInputView.inputTextView.enablesReturnKeyAutomatically = NO;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.messageInputView.inputTextView.enablesReturnKeyAutomatically = YES;
[self.messageInputView.inputTextView reloadInputViews];
});
}
break;
}
case XHBubbleMessageMediaTypePhoto: {
break;
}
case XHBubbleMessageMediaTypeVideo: {
break;
}
case XHBubbleMessageMediaTypeVoice: {
break;
}
case XHBubbleMessageMediaTypeEmotion: {
break;
}
case XHBubbleMessageMediaTypeLocalPosition: {
break;
}
default:
break;
}
}
- (void)setBackgroundColor:(UIColor *)color {
self.view.backgroundColor = color;
_messageTableView.backgroundColor = color;
}
- (void)setBackgroundImage:(UIImage *)backgroundImage {
self.messageTableView.backgroundView = nil;
self.messageTableView.backgroundView = [[UIImageView alloc] initWithImage:backgroundImage];
}
- (void)scrollToBottomAnimated:(BOOL)animated {
if (![self shouldAllowScroll])
return;
NSInteger rows = [self.messageTableView numberOfRowsInSection:0];
if (rows > 0) {
[self.messageTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows - 1 inSection:0]
atScrollPosition:UITableViewScrollPositionBottom
animated:animated];
}
}
- (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath
atScrollPosition:(UITableViewScrollPosition)position
animated:(BOOL)animated {
if (![self shouldAllowScroll])
return;
[self.messageTableView scrollToRowAtIndexPath:indexPath
atScrollPosition:position
animated:animated];
}
#pragma mark - Previte Method
- (BOOL)shouldAllowScroll {
if (self.isUserScrolling) {
if ([self.delegate respondsToSelector:@selector(shouldPreventScrollToBottomWhileUserScrolling)]
&& [self.delegate shouldPreventScrollToBottomWhileUserScrolling]) {
return NO;
}
}
return YES;
}
#pragma mark - Life Cycle
- (void)setup {
// iPhone or iPad keyboard view height set here.
self.keyboardViewHeight = (kIsiPad ? 264 : 216);
_allowsPanToDismissKeyboard = NO;
_allowsSendVoice = YES;
_allowsSendMultiMedia = YES;
_allowsSendFace = YES;
_inputViewStyle = XHMessageInputViewStyleFlat;
self.delegate = self;
self.dataSource = self;
}
- (id)init {
self = [super init];
if (self) {
[self setup];
}
return self;
}
- (void)awakeFromNib {
[self setup];
}
- (void)initilzer {
if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
self.automaticallyAdjustsScrollViewInsets = NO;
}
if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) {
self.edgesForExtendedLayout = UIRectEdgeNone;
}
// 默认设置用户滚动为NO
_isUserScrolling = NO;
// 初始化message tableView
XHMessageTableView *messageTableView = [[XHMessageTableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
messageTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
messageTableView.dataSource = self;
messageTableView.delegate = self;
messageTableView.separatorColor = [UIColor clearColor];
messageTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
BOOL shouldLoadMoreMessagesScrollToTop = YES;
if ([self.delegate respondsToSelector:@selector(shouldLoadMoreMessagesScrollToTop)]) {
shouldLoadMoreMessagesScrollToTop = [self.delegate shouldLoadMoreMessagesScrollToTop];
}
if (shouldLoadMoreMessagesScrollToTop) {
messageTableView.tableHeaderView = self.headerContainerView;
}
[self.view addSubview:messageTableView];
[self.view sendSubviewToBack:messageTableView];
_messageTableView = messageTableView;
// 设置Message TableView 的bottom edg
CGFloat inputViewHeight = (self.inputViewStyle == XHMessageInputViewStyleFlat) ? 45.0f : 40.0f;
[self setTableViewInsetsWithBottomValue:inputViewHeight];
// 设置整体背景颜色
[self setBackgroundColor:[UIColor whiteColor]];
// 输入工具条的frame
CGRect inputFrame = CGRectMake(0.0f,
self.view.frame.size.height - inputViewHeight,
self.view.frame.size.width,
inputViewHeight);
WEAKSELF
if (self.allowsPanToDismissKeyboard) {
// 控制输入工具条的位置块
void (^AnimationForMessageInputViewAtPoint)(CGPoint point) = ^(CGPoint point) {
CGRect inputViewFrame = weakSelf.messageInputView.frame;
CGPoint keyboardOrigin = [weakSelf.view convertPoint:point fromView:nil];
inputViewFrame.origin.y = keyboardOrigin.y - inputViewFrame.size.height;
weakSelf.messageInputView.frame = inputViewFrame;
};
self.messageTableView.keyboardDidScrollToPoint = ^(CGPoint point) {
if (weakSelf.textViewInputViewType == XHInputViewTypeText)
AnimationForMessageInputViewAtPoint(point);
};
self.messageTableView.keyboardWillSnapBackToPoint = ^(CGPoint point) {
if (weakSelf.textViewInputViewType == XHInputViewTypeText)
AnimationForMessageInputViewAtPoint(point);
};
self.messageTableView.keyboardWillBeDismissed = ^() {
CGRect inputViewFrame = weakSelf.messageInputView.frame;
inputViewFrame.origin.y = weakSelf.view.bounds.size.height - inputViewFrame.size.height;
weakSelf.messageInputView.frame = inputViewFrame;
};
}
// block回调键盘通知
self.messageTableView.keyboardWillChange = ^(CGRect keyboardRect, UIViewAnimationOptions options, double duration, BOOL showKeyboard) {
if (weakSelf.textViewInputViewType == XHInputViewTypeText) {
[UIView animateWithDuration:duration
delay:0.0
options:options
animations:^{
CGFloat keyboardY = [weakSelf.view convertRect:keyboardRect fromView:nil].origin.y;
CGRect inputViewFrame = weakSelf.messageInputView.frame;
CGFloat inputViewFrameY = keyboardY - inputViewFrame.size.height;
// for ipad modal form presentations
CGFloat messageViewFrameBottom = weakSelf.view.frame.size.height - inputViewFrame.size.height;
if (inputViewFrameY > messageViewFrameBottom)
inputViewFrameY = messageViewFrameBottom;
weakSelf.messageInputView.frame = CGRectMake(inputViewFrame.origin.x,
inputViewFrameY,
inputViewFrame.size.width,
inputViewFrame.size.height);
[weakSelf setTableViewInsetsWithBottomValue:weakSelf.view.frame.size.height
- weakSelf.messageInputView.frame.origin.y];
if (showKeyboard)
[weakSelf scrollToBottomAnimated:NO];
}
completion:nil];
}
};
self.messageTableView.keyboardDidChange = ^(BOOL didShowed) {
if ([weakSelf.messageInputView.inputTextView isFirstResponder]) {
if (didShowed) {
if (weakSelf.textViewInputViewType == XHInputViewTypeText) {
weakSelf.shareMenuView.alpha = 0.0;
weakSelf.emotionManagerView.alpha = 0.0;
}
}
}
};
self.messageTableView.keyboardDidHide = ^() {
[weakSelf.messageInputView.inputTextView resignFirstResponder];
};
// 初始化输入工具条
XHMessageInputView *inputView = [[XHMessageInputView alloc] initWithFrame:inputFrame];
inputView.allowsSendFace = self.allowsSendFace;
inputView.allowsSendVoice = self.allowsSendVoice;
inputView.allowsSendMultiMedia = self.allowsSendMultiMedia;
inputView.delegate = self;
[self.view addSubview:inputView];
[self.view bringSubviewToFront:inputView];
_messageInputView = inputView;
// 设置手势滑动,默认添加一个bar的高度值
self.messageTableView.messageInputBarHeight = CGRectGetHeight(_messageInputView.bounds);
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// 设置键盘通知或者手势控制键盘消失
[self.messageTableView setupPanGestureControlKeyboardHide:self.allowsPanToDismissKeyboard];
// KVO 检查contentSize
[self.messageInputView.inputTextView addObserver:self
forKeyPath:@"contentSize"
options:NSKeyValueObservingOptionNew
context:nil];
[self.messageInputView.inputTextView setEditable:YES];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if (self.textViewInputViewType != XHInputViewTypeNormal) {
[self layoutOtherMenuViewHiden:YES];
}
// remove键盘通知或者手势
[self.messageTableView disSetupPanGestureControlKeyboardHide:self.allowsPanToDismissKeyboard];
// remove KVO
[self.messageInputView.inputTextView removeObserver:self forKeyPath:@"contentSize"];
[self.messageInputView.inputTextView setEditable:NO];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
// 初始化消息页面布局
[self initilzer];
[[XHMessageBubbleView appearance] setFont:[UIFont systemFontOfSize:16.0f]];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc {
_messages = nil;
_delegate = nil;
_dataSource = nil;
_messageTableView.delegate = nil;
_messageTableView.dataSource = nil;
_messageTableView = nil;
_messageInputView = nil;
_photographyHelper = nil;
_locationHelper = nil;
}
#pragma mark - View Rotation
- (BOOL)shouldAutorotate {
return NO;
}
#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_9_0
- (NSUInteger)supportedInterfaceOrientations
#else
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
#endif
{
return UIInterfaceOrientationMaskPortrait;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return UIInterfaceOrientationPortrait;
}
#pragma mark - RecorderPath Helper Method
- (NSString *)getRecorderPath {
NSString *recorderPath = nil;
recorderPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMddHHmmssSSS"];
recorderPath = [recorderPath stringByAppendingFormat:@"%@-MySound.m4a", [dateFormatter stringFromDate:now]];
return recorderPath;
}
#pragma mark - UITextView Helper Method
- (CGFloat)getTextViewContentH:(UITextView *)textView {
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
return ceilf([textView sizeThatFits:textView.frame.size].height);
} else {
return textView.contentSize.height;
}
}
#pragma mark - Layout Message Input View Helper Method
- (void)layoutAndAnimateMessageInputTextView:(UITextView *)textView {
CGFloat maxHeight = [XHMessageInputView maxHeight];
CGFloat contentH = [self getTextViewContentH:textView];
BOOL isShrinking = contentH < self.previousTextViewContentHeight;
CGFloat changeInHeight = contentH - _previousTextViewContentHeight;
if (!isShrinking && (self.previousTextViewContentHeight == maxHeight || textView.text.length == 0)) {
changeInHeight = 0;
}
else {
changeInHeight = MIN(changeInHeight, maxHeight - self.previousTextViewContentHeight);
}
if (changeInHeight != 0.0f) {
[UIView animateWithDuration:0.25f
animations:^{
[self setTableViewInsetsWithBottomValue:self.messageTableView.contentInset.bottom + changeInHeight];
[self scrollToBottomAnimated:NO];
if (isShrinking) {
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0) {
self.previousTextViewContentHeight = MIN(contentH, maxHeight);
}
// if shrinking the view, animate text view frame BEFORE input view frame
[self.messageInputView adjustTextViewHeightBy:changeInHeight];
}
CGRect inputViewFrame = self.messageInputView.frame;
self.messageInputView.frame = CGRectMake(0.0f,
inputViewFrame.origin.y - changeInHeight,
inputViewFrame.size.width,
inputViewFrame.size.height + changeInHeight);
if (!isShrinking) {
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0) {
self.previousTextViewContentHeight = MIN(contentH, maxHeight);
}
// growing the view, animate the text view frame AFTER input view frame
[self.messageInputView adjustTextViewHeightBy:changeInHeight];
}
}
completion:^(BOOL finished) {
}];
self.previousTextViewContentHeight = MIN(contentH, maxHeight);
}
// Once we reached the max height, we have to consider the bottom offset for the text view.
// To make visible the last line, again we have to set the content offset.
if (self.previousTextViewContentHeight == maxHeight) {
double delayInSeconds = 0.01;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime,
dispatch_get_main_queue(),
^(void) {
CGPoint bottomOffset = CGPointMake(0.0f, contentH - textView.bounds.size.height);
[textView setContentOffset:bottomOffset animated:YES];
});
}
}
#pragma mark - Scroll Message TableView Helper Method
- (void)setTableViewInsetsWithBottomValue:(CGFloat)bottom {
UIEdgeInsets insets = [self tableViewInsetsWithBottomValue:bottom];
self.messageTableView.contentInset = insets;
self.messageTableView.scrollIndicatorInsets = insets;
}
- (UIEdgeInsets)tableViewInsetsWithBottomValue:(CGFloat)bottom {
UIEdgeInsets insets = UIEdgeInsetsZero;
if ([self respondsToSelector:@selector(topLayoutGuide)]) {
insets.top = self.topLayoutGuide.length;
}
insets.bottom = bottom;
return insets;
}
#pragma mark - Message Calculate Cell Height
- (CGFloat)calculateCellHeightWithMessage:(id <XHMessageModel>)message atIndexPath:(NSIndexPath *)indexPath {
CGFloat cellHeight = 0;
BOOL displayTimestamp = YES;
if ([self.delegate respondsToSelector:@selector(shouldDisplayTimestampForRowAtIndexPath:)]) {
displayTimestamp = [self.delegate shouldDisplayTimestampForRowAtIndexPath:indexPath];
}
cellHeight = [XHMessageTableViewCell calculateCellHeightWithMessage:message displaysTimestamp:displayTimestamp];
return cellHeight;
}
#pragma mark - Message Send helper Method
- (void)didSendMessageWithText:(NSString *)text {
DLog(@"send text : %@", text);
if ([self.delegate respondsToSelector:@selector(didSendText:fromSender:onDate:)]) {
[self.delegate didSendText:text fromSender:self.messageSender onDate:[NSDate date]];
}
}
- (void)didSendMessageWithPhoto:(UIImage *)photo {
DLog(@"send photo : %@", photo);
if ([self.delegate respondsToSelector:@selector(didSendPhoto:fromSender:onDate:)]) {
[self.delegate didSendPhoto:photo fromSender:self.messageSender onDate:[NSDate date]];
}
}
- (void)didSendMessageWithVideoConverPhoto:(UIImage *)videoConverPhoto videoPath:(NSString *)videoPath {
DLog(@"send videoPath : %@ videoConverPhoto : %@", videoPath, videoConverPhoto);
if ([self.delegate respondsToSelector:@selector(didSendVideoConverPhoto:videoPath:fromSender:onDate:)]) {
[self.delegate didSendVideoConverPhoto:videoConverPhoto videoPath:videoPath fromSender:self.messageSender onDate:[NSDate date]];
}
}
- (void)didSendMessageWithVoice:(NSString *)voicePath voiceDuration:(NSString*)voiceDuration {
DLog(@"send voicePath : %@", voicePath);
if ([self.delegate respondsToSelector:@selector(didSendVoice:voiceDuration:fromSender:onDate:)]) {
[self.delegate didSendVoice:voicePath voiceDuration:voiceDuration fromSender:self.messageSender onDate:[NSDate date]];
}
}
- (void)didSendEmotionMessageWithEmotionPath:(NSString *)emotionPath {
DLog(@"send emotionPath : %@", emotionPath);
if ([self.delegate respondsToSelector:@selector(didSendEmotion:fromSender:onDate:)]) {
[self.delegate didSendEmotion:emotionPath fromSender:self.messageSender onDate:[NSDate date]];
}
}
- (void)didSendGeolocationsMessageWithGeolocaltions:(NSString *)geolcations location:(CLLocation *)location {
DLog(@"send geolcations : %@", geolcations);
if ([self.delegate respondsToSelector:@selector(didSendGeoLocationsPhoto:geolocations:location:fromSender:onDate:)]) {
[self.delegate didSendGeoLocationsPhoto:[UIImage imageNamed:@"Fav_Cell_Loc"] geolocations:geolcations location:location fromSender:self.messageSender onDate:[NSDate date]];
}
}
#pragma mark - Other Menu View Frame Helper Mehtod
- (void)layoutOtherMenuViewHiden:(BOOL)hide {
[self.messageInputView.inputTextView resignFirstResponder];
[UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
__block CGRect inputViewFrame = self.messageInputView.frame;
__block CGRect otherMenuViewFrame;
void (^InputViewAnimation)(BOOL hide) = ^(BOOL hide) {
inputViewFrame.origin.y = (hide ? (CGRectGetHeight(self.view.bounds) - CGRectGetHeight(inputViewFrame)) : (CGRectGetMinY(otherMenuViewFrame) - CGRectGetHeight(inputViewFrame)));
self.messageInputView.frame = inputViewFrame;
};
void (^EmotionManagerViewAnimation)(BOOL hide) = ^(BOOL hide) {
otherMenuViewFrame = self.emotionManagerView.frame;
otherMenuViewFrame.origin.y = (hide ? CGRectGetHeight(self.view.frame) : (CGRectGetHeight(self.view.frame) - CGRectGetHeight(otherMenuViewFrame)));
self.emotionManagerView.alpha = !hide;
self.emotionManagerView.frame = otherMenuViewFrame;
};
void (^ShareMenuViewAnimation)(BOOL hide) = ^(BOOL hide) {
otherMenuViewFrame = self.shareMenuView.frame;
otherMenuViewFrame.origin.y = (hide ? CGRectGetHeight(self.view.frame) : (CGRectGetHeight(self.view.frame) - CGRectGetHeight(otherMenuViewFrame)));
self.shareMenuView.alpha = !hide;
self.shareMenuView.frame = otherMenuViewFrame;
};
if (hide) {
switch (self.textViewInputViewType) {
case XHInputViewTypeEmotion: {
EmotionManagerViewAnimation(hide);
break;
}
case XHInputViewTypeShareMenu: {
ShareMenuViewAnimation(hide);
break;
}
default:
break;
}
} else {
// 这里需要注意block的执行顺序,因为otherMenuViewFrame是公用的对象,所以对于被隐藏的Menu的frame的origin的y会是最大值
switch (self.textViewInputViewType) {
case XHInputViewTypeEmotion: {
// 1、先隐藏和自己无关的View
ShareMenuViewAnimation(!hide);
// 2、再显示和自己相关的View
EmotionManagerViewAnimation(hide);
break;
}
case XHInputViewTypeShareMenu: {
// 1、先隐藏和自己无关的View
EmotionManagerViewAnimation(!hide);
// 2、再显示和自己相关的View
ShareMenuViewAnimation(hide);
break;
}
default:
break;
}
}
InputViewAnimation(hide);
[self setTableViewInsetsWithBottomValue:self.view.frame.size.height
- self.messageInputView.frame.origin.y];
[self scrollToBottomAnimated:NO];
} completion:^(BOOL finished) {
if (hide) {
self.textViewInputViewType = XHInputViewTypeNormal;
}
}];
}
#pragma mark - Voice Recording Helper Method
- (void)prepareRecordWithCompletion:(XHPrepareRecorderCompletion)completion {
[self.voiceRecordHelper prepareRecordingWithPath:[self getRecorderPath] prepareRecorderCompletion:completion];
}
- (void)startRecord {
[self.voiceRecordHUD startRecordingHUDAtView:self.view];
[self.voiceRecordHelper startRecordingWithStartRecorderCompletion:^{
}];
}
- (void)finishRecorded {
WEAKSELF
[self.voiceRecordHUD stopRecordCompled:^(BOOL fnished) {
weakSelf.voiceRecordHUD = nil;
}];
[self.voiceRecordHelper stopRecordingWithStopRecorderCompletion:^{
[weakSelf didSendMessageWithVoice:weakSelf.voiceRecordHelper.recordPath voiceDuration:weakSelf.voiceRecordHelper.recordDuration];
}];
}
- (void)pauseRecord {
[self.voiceRecordHUD pauseRecord];
}
- (void)resumeRecord {
[self.voiceRecordHUD resaueRecord];
}
- (void)cancelRecord {
WEAKSELF