IM界面输入框及键盘实现

上篇已经能够收发消息了,这篇将讲解如何实现聊天界面的键盘功能,效果图如下

效果图.gif

该界面分为两个部分,上部分是显示消息流,而下部分是一个工具栏其包括语音按钮输入框表情按钮更多按钮等视图。上部分用一个tableView就可以实现了,而下部分如何封装?好我们先看工具栏结构,细看其分为两个部分,从上到下看;上部分为语音按钮、输入框、表情按钮、更多按钮;下部分是表情页、更多页的详情视图。其示意图如下

工具栏.png

好现在我们就用代码来实现上面的结构:

//LXChatViewController.m
@interface LXChatViewController ()

@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) {
        
    }];
}

消息流界面中关键代码是在ControllerviewWillAppear注册通知,在viewWillDisappear移除通知,显示键盘和隐藏键盘时tableView动画其实是修改它的contentInset来实现;然后再设置了bar的delegate。再看工具栏的关键代码具体实现

#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) {
        // 显示系统键盘
        [self.textView becomeFirstResponder];
        return;
    }
    if (self.showType == LXBarViewShowTypeAudio) {
        //
        
        // 显示emoji键盘
        [self showEmoji:false];
        return;
    }
    if (self.showType == LXBarViewShowTypeText) {
        self.showType = LXBarViewShowTypeEmoji;
        // 隐藏系统键盘
        [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) {
        // 显示系统键盘
        [self.textView becomeFirstResponder];
        return;
    }
    if (self.showType == LXBarViewShowTypeAudio) {
        // 隐藏语音相关
        
        // 弹起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;
        // 隐藏系统键盘
        [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) {
        // 显示系统键盘
        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 {
            // 显示结束
            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];
    }
}

到此工具栏上的语音、表情、更多按钮的事件处理已经完成;看效果图输入框是随着输入的字符其高度也会发生变化,因此需要自定义一个UITextView,并且需要将其高度变化的回调传到外部。

// 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 *)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高度变化其实是监听其contentSize的变化而做出具体的改变,另外scrollRectToVisible:animated:滚动到底部如果不延迟执行不起作用,具体是什么原因笔者也不知道,如有知悉者还请告知,甚是感谢。到此工具栏上部分的功能基本已经实现,接下来是实现表情更多的详情页。
表情的详情页其实是由一个UICollectionViewUIPageControl底部视图构成,其中需要自定义UICollectionViewlayout,如何实现这个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 *)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内所有的cell的布局属性
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect;
// 返回某个indexPath下的cell的布局属性,在这里我们改了其frame
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath;

你可能感兴趣的:(IM界面输入框及键盘实现)