上篇已經(jīng)能夠收發(fā)消息了埂奈,這篇將講解如何實現(xiàn)聊天界面的鍵盤功能嗜湃,效果圖如下
該界面分為兩個部分
奈应,上部分是顯示消息流
,而下部分是一個工具欄
其包括語音按鈕
购披、輸入框
杖挣、表情按鈕
、更多按鈕
等視圖刚陡。上部分用一個tableView
就可以實現(xiàn)了惩妇,而下部分如何封裝
?好我們先看工具欄
的結(jié)構(gòu)
筐乳,細(xì)看其分為兩個部分
歌殃,從上到下看;上部分
為語音按鈕蝙云、輸入框氓皱、表情按鈕、更多按鈕勃刨;下部分
是表情頁波材、更多頁的詳情視圖。其示意圖如下
好現(xiàn)在我們就用代碼來實現(xiàn)上面的結(jié)構(gòu):
//LXChatViewController.m
@interface LXChatViewController ()<UITableViewDelegate, UITableViewDataSource, LXChatBarViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) LXChatBarView *barView;
@end
@implementation LXChatViewController
#pragma mark - life cycle
- (void)viewDidLoad {
//
UITableView *tableView = [[UITableView alloc] initWithFrame:tbRect style:UITableViewStylePlain];
...
[self.view addSubview:tableView];
CGRect barRect = CGRectMake(inset.left, CGRectGetMaxY(tbRect), CGRectGetWidth(deviceBounds), 50 + 250 + LXGlobalDefined.safeInset.bottom);
LXChatBarView *barView = [[LXChatBarView alloc] initWithFrame:barRect];
barView.delegate = self;
[self.view addSubview:barView];
self.barView = barView;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHiden:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - notification
- (void)keyboardWillShow:(NSNotification *)notification {
//LXLog(@"show keyboard %@", notification);
CGRect keyboardBeginFrame = [notification.userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
CGRect keyboardEndFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
LXLog(@"begin frame %@, end frame %@", NSStringFromCGRect(keyboardBeginFrame), NSStringFromCGRect(keyboardEndFrame));
CGSize size = keyboardEndFrame.size;
CGRect barFrame = self.barView.frame;
UIEdgeInsets inset = LXGlobalDefined.safeInset;
CGFloat distance = size.height - inset.bottom + self.barView.barHeight - 50;
CGFloat barY = LXdeviceHeight - size.height - self.barView.barHeight;
[UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
self.barView.frame = CGRectMake(barFrame.origin.x, barY, barFrame.size.width, barFrame.size.height);
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, distance + insetBottom, 0);
if (self.list.count > 0) {
[self scrollToListBottomWithAnimation:false needReloadList:false];
}
} completion:^(BOOL finished) {
}];
}
- (void)keyboardWillHiden:(NSNotification *)notification {
//LXLog(@"hiden keyboard %@", notification);
LXBarViewShowType type = self.barView.showType;
if (type == LXBarViewShowTypeMore || type == LXBarViewShowTypeEmoji) {
return;
}
CGRect beginFrame = [notification.userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
CGRect endFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
LXLog(@"begin frame %@, end frame %@", NSStringFromCGRect(beginFrame), NSStringFromCGRect(endFrame));
CGRect barFrame = self.barView.frame;
UIEdgeInsets inset = LXGlobalDefined.safeInset;
CGFloat barY = LXdeviceHeight - inset.bottom - self.barView.barHeight;
[UIView animateWithDuration:0.25 animations:^{
self.barView.frame = CGRectMake(barFrame.origin.x, barY, barFrame.size.width, barFrame.size.height);
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, insetBottom + self.barView.barHeight - 50, 0);
}];
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
//UIKeyboardWillHideNotification
if (self.barView.showType == LXBarViewShowTypeText) {
[self.view endEditing:true];
} else if (self.barView.showType == LXBarViewShowTypeMore) {
CGSize size = self.barView.moreView.frame.size;
[self hidenKeyboardSize:size];
} else if (self.barView.showType == LXBarViewShowTypeEmoji) {
CGSize size = self.barView.emojiView.frame.size;
[self hidenKeyboardSize:size];
} else if (self.barView.showType == LXBarViewShowTypeAudio) {
return;
}
self.barView.showType = LXBarViewShowTypeNone;
}
- (void)hidenKeyboardSize:(CGSize)size {
CGRect barFrame = self.barView.frame;
UIEdgeInsets inset = LXGlobalDefined.safeInset;
CGFloat barY = LXdeviceHeight - self.barView.barHeight - inset.bottom;
[UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
self.barView.frame = CGRectMake(barFrame.origin.x, barY, CGRectGetWidth(barFrame), CGRectGetHeight(barFrame));
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, insetBottom + self.barView.barHeight - 50, 0);
} completion:^(BOOL finished) {
self.barView.emojiView.hidden = true;
self.barView.moreView.hidden = true;
}];
}
#pragma mark - LXChatBarViewDelegate
- (void)barView:(LXChatBarView *)barView willShowKeyboard:(LXBarViewShowType)type size:(CGSize)size {
CGRect barFrame = self.barView.frame;
UIEdgeInsets inset = LXGlobalDefined.safeInset;
CGFloat distance = size.height + barView.barHeight - 50;
CGFloat barY = LXdeviceHeight - size.height - barView.barHeight - inset.bottom;
[UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
self.barView.frame = CGRectMake(barFrame.origin.x, barY, barFrame.size.width, barFrame.size.height);
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, distance + insetBottom, 0);
if (self.list.count > 0) {
[self scrollToListBottomWithAnimation:false needReloadList:false];
}
} completion:^(BOOL finished) {
}];
}
- (void)barView:(LXChatBarView *)barView willHidenKeyboard:(LXBarViewShowType)type size:(CGSize)size {
CGRect barFrame = self.barView.frame;
UIEdgeInsets inset = LXGlobalDefined.safeInset;
CGFloat barY = LXdeviceHeight - barView.barHeight - inset.bottom;
[UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
self.barView.frame = CGRectMake(barFrame.origin.x, barY, CGRectGetWidth(barFrame), CGRectGetHeight(barFrame));
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, insetBottom, 0);
} completion:^(BOOL finished) {
self.barView.emojiView.hidden = true;
self.barView.moreView.hidden = true;
}];
}
- (void)barView:(LXChatBarView *)barView barHeightWillChange:(CGFloat)height {
UIEdgeInsets inset = self.tableView.contentInset;
[UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, inset.bottom - height, 0);
if (self.list.count > 0) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.list.count - 1 inSection:0];
[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:false];
}
} completion:^(BOOL finished) {
}];
}
消息流界面中關(guān)鍵代碼是在Controller
的viewWillAppear
注冊通知身隐,在viewWillDisappear
移除通知廷区,顯示鍵盤和隱藏鍵盤時tableView
的動畫
其實是修改它的contentInset
來實現(xiàn);然后再設(shè)置了bar的delegate
贾铝。再看工具欄的關(guān)鍵代碼具體實現(xiàn)
#pragma mark - event
- (void)setTextViewIfneed {
if (self.text) {
self.textView.text = self.text;
}
}
- (void)tapEmoji:(UIButton *)button {
[self setTextViewIfneed];
if (self.showType == LXBarViewShowTypeMore) {
// 隱藏more鍵盤
self.moreView.hidden = true;
// 顯示emoji鍵盤
[self showEmoji:true];
return;
}
if (self.showType == LXBarViewShowTypeEmoji) {
// 顯示系統(tǒng)鍵盤
[self.textView becomeFirstResponder];
return;
}
if (self.showType == LXBarViewShowTypeAudio) {
//
// 顯示emoji鍵盤
[self showEmoji:false];
return;
}
if (self.showType == LXBarViewShowTypeText) {
self.showType = LXBarViewShowTypeEmoji;
// 隱藏系統(tǒng)鍵盤
[self.textView resignFirstResponder];
}
// 顯示emoji鍵盤
[self showEmoji:false];
}
- (void)showEmoji:(BOOL)animated {
self.emojiView.hidden = false;
self.moreView.hidden = true;
CGSize size = self.emojiView.frame.size;
if ([self.delegate respondsToSelector:@selector(barView:willShowKeyboard:size:)]) {
[self.delegate barView:self willShowKeyboard:LXBarViewShowTypeEmoji size:size];
}
self.showType = LXBarViewShowTypeEmoji;
[self.emojiBtn setImage:[UIImage imageNamed:@"keyboard"] forState:UIControlStateNormal];
if (animated) {
CGRect frame = self.emojiView.frame;
CGRect begin = CGRectMake(CGRectGetMinX(frame), CGRectGetHeight(frame), CGRectGetWidth(frame), CGRectGetHeight(frame));
self.emojiView.frame = begin;
[UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
self.emojiView.frame = frame;
} completion:^(BOOL finished) {
}];
}
}
- (void)reEmojiInit {
[self.emojiBtn setImage:[UIImage imageNamed:@"emoji"] forState:UIControlStateNormal];
}
- (void)tapMore:(UIButton *)button {
[self setTextViewIfneed];
if (self.showType == LXBarViewShowTypeMore) {
// 顯示系統(tǒng)鍵盤
[self.textView becomeFirstResponder];
return;
}
if (self.showType == LXBarViewShowTypeAudio) {
// 隱藏語音相關(guān)
// 彈起more鍵盤
[self showMore:false];
return;
}
if (self.showType == LXBarViewShowTypeEmoji) {
// 隱藏emoji鍵盤
self.emojiView.hidden = true;
// 彈起more鍵盤
[self showMore:true];
return;
}
if (self.showType == LXBarViewShowTypeText) {
self.showType = LXBarViewShowTypeMore;
// 隱藏系統(tǒng)鍵盤
[self.textView resignFirstResponder];
}
// 彈起more鍵盤
[self showMore:false];
}
- (void)showMore:(BOOL)animated {
self.moreView.hidden = false;
self.emojiView.hidden = true;
if ([self.delegate respondsToSelector:@selector(barView:willShowKeyboard:size:)]) {
CGSize size = self.moreView.bounds.size;
[self.delegate barView:self willShowKeyboard:LXBarViewShowTypeMore size:size];
}
self.showType = LXBarViewShowTypeMore;
if (animated) {
CGRect frame = self.moreView.frame;
CGRect begin = CGRectMake(CGRectGetMinX(frame), CGRectGetHeight(frame), CGRectGetWidth(frame), CGRectGetHeight(frame));
self.moreView.frame = begin;
[UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
self.moreView.frame = frame;
} completion:^(BOOL finished) {
}];
}
}
- (void)tapAudio:(UIButton *)button {
if (self.showType == LXBarViewShowTypeAudio) {
// 顯示系統(tǒng)鍵盤
self.textView.text = self.text;
[self.textView becomeFirstResponder];
return;
}
self.textView.text = nil;
if (self.showType == LXBarViewShowTypeEmoji || self.showType == LXBarViewShowTypeMore) {
// 獲取size
CGSize size = self.showType == LXBarViewShowTypeEmoji? self.emojiView.frame.size: self.moreView.frame.size;
// 隱藏
if ([self.delegate respondsToSelector:@selector(barView:willHidenKeyboard:size:)]) {
[self.delegate barView:self willHidenKeyboard:self.showType size:size];
}
[self showAudio];
return;
}
[self showAudio];
[self.textView resignFirstResponder];
}
- (void)showAudio {
self.showType = LXBarViewShowTypeAudio;
//
[self.audioBtn setImage:[UIImage imageNamed:@"keyboard"] forState:UIControlStateNormal];
//
self.placeLabel.hidden = false;
self.placeLabel.text = LXAudioPressTalk;
}
- (void)reAudioInit {
//
[self.audioBtn setImage:[UIImage imageNamed:@"audio"] forState:UIControlStateNormal];
//
self.placeLabel.hidden = true;
}
- (void)pressAudio:(UILongPressGestureRecognizer *)gesture {
UIGestureRecognizerState state = gesture.state;
CGPoint point = CGPointZero;
switch (state) {
case UIGestureRecognizerStateBegan: {
LXLog(@"begin press");
break;
}
case UIGestureRecognizerStateChanged: {
//LXLog(@"changed");
CGPoint temp = [gesture locationInView:self];
LXLog(@"point = %@", NSStringFromCGPoint(temp));
point = temp;
break;
}
case UIGestureRecognizerStateCancelled: {
LXLog(@"cancelled");
break;
}
case UIGestureRecognizerStateFailed: {
LXLog(@"failed");
break;
}
case UIGestureRecognizerStateEnded: {
LXLog(@"ended");
break;
}
default:
break;
}
[self showAudioTipViewBy:state pressPoint:point];
}
- (void)showAudioTipViewBy:(UIGestureRecognizerState)state pressPoint:(CGPoint)point {
if (state == UIGestureRecognizerStateBegan) {
self.recoderState = LXAudioRecoderStateBegin;
self.placeLabel.text = LXAudioOutEnd;
[self.audioRecoder record];
if ([self.audioTipView superview]) {
return;
}
CGRect dBounds = [UIScreen mainScreen].bounds;
CGFloat wh = 120.0;
CGFloat x = (CGRectGetWidth(dBounds) - wh) / 2;
CGFloat y = (CGRectGetHeight(dBounds) - wh) / 2;
self.audioTipView.frame = CGRectMake(x, y, wh, wh);
self.audioTipView.image = [UIImage imageNamed:@"pressAudio"];
[[UIApplication sharedApplication].keyWindow addSubview:self.audioTipView];
} else if (state == UIGestureRecognizerStateChanged) {
if (point.y < 0 || point.y > self.frame.size.height) {
// 顯示取消
self.placeLabel.text = LXAudioOutCancel;
self.audioTipView.image = [UIImage imageNamed:@"cancelAudio"];
self.recoderState = LXAudioRecoderStateWillCancel;
} else {
// 顯示結(jié)束
self.placeLabel.text = LXAudioOutEnd;
self.audioTipView.image = [UIImage imageNamed:@"pressAudio"];
self.recoderState = LXAudioRecoderStateWillEnd;
}
} else if (state == UIGestureRecognizerStateEnded) {
[self.audioTipView removeFromSuperview];
self.placeLabel.text = LXAudioPressTalk;
[self.audioRecoder stop];
}
}
#pragma mark - getter/setter
- (void)setShowType:(LXBarViewShowType)showType {
_showType = showType;
if (showType == LXBarViewShowTypeAudio) {
[self reEmojiInit];
} else if (showType == LXBarViewShowTypeEmoji) {
[self reAudioInit];
} else {
[self reEmojiInit];
[self reAudioInit];
}
}
到此工具欄上的語音隙轻、表情、更多按鈕的事件處理已經(jīng)完成忌傻;看效果圖輸入框是隨著輸入的字符其高度也會發(fā)生變化大脉,因此需要自定義一個UITextView
搞监,并且需要將其高度變化的回調(diào)傳到外部水孩。
// LXTextView.h
typedef void(^LXTextViewHeightChange)(CGFloat height);
@interface LXTextView : UITextView
@property (nonatomic, assign) CGFloat maxHeight;
@property (nonatomic, copy) LXTextViewHeightChange heightChangeCallback;
@end
// LXTextView.m
static void *LXContentSizeContext = &LXContentSizeContext;
@interface LXTextView ()
@property (nonatomic, assign) CGFloat originHeight;
@property (nonatomic, assign) UIEdgeInsets inset;
@end
@implementation LXTextView
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.layer.borderColor = UIColor.lightGrayColor.CGColor;
self.layer.borderWidth = 1.0;
self.maxHeight = 90;
self.originHeight = CGRectGetHeight(frame);
self.autocapitalizationType = UITextAutocapitalizationTypeNone;
self.autocorrectionType = UITextAutocorrectionTypeNo;
self.enablesReturnKeyAutomatically = true;
self.layoutManager.allowsNonContiguousLayout = false;
self.font = [UIFont systemFontOfSize:14.0];
[self addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:LXContentSizeContext];
}
return self;
}
- (instancetype)init {
return [self initWithFrame:CGRectZero];
}
- (void)dealloc {
[self removeObserver:self forKeyPath:@"contentSize"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"contentSize"]) {
LXLog(@"%@", change);
CGSize newSize = [change[@"new"] CGSizeValue];
CGSize oldSize = [change[@"old"] CGSizeValue];
if (newSize.height != oldSize.height) {
//
LXLog(@"高度變化");
CGFloat height = newSize.height > self.originHeight? newSize.height: self.originHeight;
height = height < self.maxHeight? height: self.maxHeight;
if (self.heightChangeCallback) {
self.heightChangeCallback(height);
//[self scrollRangeToVisible:NSMakeRange(self.text.length, 1)];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
CGRect visible = CGRectMake(0, self.contentSize.height - 15, self.contentSize.width, 15);
[self scrollRectToVisible:visible animated:false];
});
}
}
}
}
@end
textView
高度變化其實是監(jiān)聽其contentSize
的變化而做出具體的改變,另外scrollRectToVisible:animated:
滾動到底部如果不延遲執(zhí)行不起作用
琐驴,具體是什么原因筆者也不知道俘种,如有知悉者還請告知,甚是感謝绝淡。到此工具欄上部分的功能基本已經(jīng)實現(xiàn)宙刘,接下來是實現(xiàn)表情
、更多
的詳情頁牢酵。
表情的詳情頁其實是由一個UICollectionView
悬包、UIPageControl
、底部視圖
構(gòu)成馍乙,其中需要自定義UICollectionView
的layout
布近,如何實現(xiàn)這個layout
呢垫释?請看具體代碼
// LXEmojiLayout.h
@interface LXEmojiLayout : UICollectionViewLayout
@property (nonatomic, assign) UIEdgeInsets sectionInset;
@property (nonatomic, assign) CGSize itemSize;
@property (nonatomic, assign) CGFloat linePadding;
@property (nonatomic, assign) CGFloat itemPadding;
@end
// LXEmojiLayout.m
@interface LXEmojiLayout ()
@property (nonatomic, assign) CGFloat totalWidth;
@property (nonatomic, strong) NSMutableArray *attrsArr;
@end
@implementation LXEmojiLayout
- (void)prepareLayout {
[super prepareLayout];
self.totalWidth = 0;
NSMutableArray *attributesArr = [NSMutableArray array];
NSInteger sectionCount = [self.collectionView numberOfSections];
for (int i = 0; i < sectionCount; i++) {
NSInteger itemCount = [self.collectionView numberOfItemsInSection:i];
for (int j = 0; j < itemCount; j++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:j inSection:i];
UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:indexPath];
[attributesArr addObject:attrs];
}
}
self.attrsArr = attributesArr;
}
//
- (CGSize)collectionViewContentSize {
NSInteger sectionCount = [self.collectionView numberOfSections];
CGFloat pageWidth = self.collectionView.bounds.size.width;
return CGSizeMake(sectionCount * pageWidth, self.collectionView.bounds.size.height);
}
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
return self.attrsArr;
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
CGFloat pageWidth = self.collectionView.bounds.size.width;
CGSize itemSize = self.itemSize;
CGFloat lPadding = self.linePadding;
CGFloat hPadding = self.itemPadding;
NSInteger index = indexPath.row % 8;
NSInteger line = indexPath.row / 8;
CGFloat x = indexPath.section * pageWidth + self.sectionInset.left + index * (itemSize.width + hPadding);
CGFloat y = self.sectionInset.top + line * (itemSize.height + lPadding);
layoutAttributes.frame = CGRectMake(x, y, itemSize.width, itemSize.height);
return layoutAttributes;
}
@end
從代碼上看LXEmojiLayout
是繼承UICollectionViewLayout
,并重寫了以下方法
// 初始化撑瞧,在這里我們保存了cell的布局屬性
- (void)prepareLayout;
// 返回collectionView的contentSize
- (CGSize)collectionViewContentSize;
// 返回rect內(nèi)所有的cell的布局屬性
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect;
// 返回某個indexPath下的cell的布局屬性棵譬,在這里我們改了其frame
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath;