转载地址: [简书地址](http://www.jianshu.com/users/23d0ae412e19/latest_articles)
实现了, 自定义气泡,文本消息的基本展示。 效果图如下。
点击 最下面的 textView 实现自动上拉,显示出下面的一个UIView,这个UIview按道理会显示出更多,表情这样的视图组件出来。 具体代码如下:
#import "ViewController.h"
#import "TalkCell.h"
#import "TalkMessage.h"
@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITextViewDelegate>
@property (nonatomic,strong) NSMutableArray *array;
@property (nonatomic,strong) TalkMessage *talkMsg;
@property (nonatomic,strong) UICollectionView *collection;
@property (nonatomic,assign) bool flag;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
_array = [[NSMutableArray alloc]init];
for (int i = 0; i < 20; i++) {
TalkMessage *talkMessage = [[TalkMessage alloc]init];
talkMessage.messageBubbleType = MessageBubbleTypeText;
if (i%2 == 0) {
talkMessage.flag = YES ;
talkMessage.talkContent = [NSString stringWithFormat:@"%d-->号新秀,iOS坚持多长时间了",i];
}else{
talkMessage.flag = NO;
talkMessage.talkContent = @"战斗力都是5的渣渣";
}
[_array addObject:talkMessage];
}
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
layout.scrollDirection = UICollectionViewScrollDirectionVertical;
layout.minimumLineSpacing = 0;
layout.minimumInteritemSpacing = 0;
_collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height) collectionViewLayout:layout];
_collection.delegate = self;
_collection.dataSource = self;
_collection.backgroundColor = [UIColor grayColor];
_collection.contentInset = UIEdgeInsetsMake(0, 0, 100, 0);
[_collection registerClass:[TalkCell class] forCellWithReuseIdentifier:@"talkCell"];
[self.view addSubview:_collection];
// 默认移动到最后一项
[_collection scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_array.count - 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:true];
// 监控contentSize的变化, 好移动UIScrollView
[_collection addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
UITextView *field = [[UITextView alloc]init];
field.frame = CGRectMake(0, self.view.bounds.size.height - 50, self.view.bounds.size.width, 50);
field.backgroundColor = [UIColor orangeColor];
field.delegate = self;
[self.view bringSubviewToFront:field];
[self.view addSubview:field];
UIView *view = [[UIView alloc]init];
view.frame = CGRectMake(0, self.view.bounds.size.height, self.view.bounds.size.width, 300);
view.backgroundColor = [UIColor purpleColor];
[self.view addSubview:view];
}
#pragma mark UITextFieldDelegate
- (void)textViewDidChange:(UITextView *)textView{
[UIView animateWithDuration:1 animations:^{
self.view.frame = CGRectMake(0, -300, self.view.bounds.size.width, self.view.bounds.size.height);
} completion:^(BOOL finished) {
[self handlerBusiness];
}];
}
#pragma mark -- scrollViewDelegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
if (self.view.frame.origin.y == 0) {
return;
}
[UIView animateWithDuration:1 animations:^{
self.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
} completion:^(BOOL finished) {
[_collection scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_array.count -1 inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:true];
}];
}
- (void)handlerBusiness{
TalkMessage *talkMessage = [[TalkMessage alloc]init];
talkMessage.messageBubbleType = MessageBubbleTypeText;
talkMessage.flag = YES;
talkMessage.talkContent = @"战斗力都是25的渣渣";
[_array addObject:talkMessage];
[_collection reloadData];
[_collection scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_array.count -1 inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:true];
}
#pragma mark UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return _array.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
_talkMsg = [_array objectAtIndex:indexPath.row];
TalkCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"talkCell" forIndexPath:indexPath];
cell.backgroundColor = [UIColor grayColor];
cell.message = _talkMsg;
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
CGSize itemSize = CGSizeMake(self.view.bounds.size.width, 80);
return itemSize;
}
// 监控 这个值的变化。 KVO 处理。
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
if ([keyPath isEqualToString:@"contentSize"]) {
NSLog(@"正在监控中........");
}
}
@end
#import <UIKit/UIKit.h>
#import "TalkMessage.h"
@interface TalkCell : UICollectionViewCell
@property (nonatomic,strong) TalkMessage *message;
@end
#import "TalkCell.h"
#import "BubbleView.h"
#import "UIView+FrameLayout.h"
#import "UIImage+Addition.h"
#import "BubbleTextView.h"
@interface TalkCell()
// 头像
@property (nonatomic,strong) UIImageView *avateImageV;
// 昵称
@property (nonatomic,strong) UILabel *nameLabel;
// 聊天的气泡,包含所有的消息类型
@property (nonatomic,strong) BubbleView *bubbleImageV;
// 消息发送状态
@property (nonatomic,strong) UIView *messageSendStateView;
@end
@implementation TalkCell
- (void)awakeFromNib{
}
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
[self setUpUi];
}
return self;
}
- (void)setUpUi{
_avateImageV = [[UIImageView alloc]init];
_avateImageV.image = [UIImage imageNamed:@"3.jpg"];
_avateImageV.layer.cornerRadius = 45/2;
_avateImageV.layer.masksToBounds = YES;
_avateImageV.userInteractionEnabled = YES;
_bubbleImageV = [[BubbleView alloc]init];
_bubbleImageV.backgroundColor = [UIColor clearColor];
_messageSendStateView = [[UIView alloc]init];
[self.contentView addSubview:_avateImageV];
[self.contentView addSubview:_bubbleImageV];
[self.contentView addSubview:_messageSendStateView];
}
#define KTopMargin 10
#define KLeftMargin 12
// 根据不同的标示显示出不同的组件的位置。
- (void)setMessage:(TalkMessage *)message{
_message = message;
if (message.flag) { // 左边
_avateImageV.frame = CGRectMake(self.width0-45-KLeftMargin, KTopMargin, 45, 45);
[_bubbleImageV setBubbleImage:[UIImage imageWithColor:[[UIColor orangeColor] colorWithAlphaComponent:0.45]] isSender:YES];
}else{// 右边
_avateImageV.frame = CGRectMake(KLeftMargin, KTopMargin, 45, 45);
[self.bubbleImageV setBubbleImage:[UIImage imageWithColor:[[UIColor whiteColor] colorWithAlphaComponent:0.45]] isSender:NO];
}
//bubbleImageV中的视图是不确定的,所以不打算复用,每次赋值移除之前视图,重新加新视图,复用会重叠问题。
[self.bubbleImageV.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
// 判断类型
switch (message.messageBubbleType) {
case MessageBubbleTypeText:{
BubbleTextView *bubbleView = [BubbleTextView BubbleTextView];
bubbleView.message = message;
[self.bubbleImageV addSubview:bubbleView];
CGSize size = [self makeRect];
//注意self.bubbleImageV是在内部bubble的size.width上增加间距定的frame
if (_message.flag) {
self.bubbleImageV.frame = CGRectMake(CGRectGetMinX(self.avateImageV.frame)-(size.width+2*KLeftMargin)-10,KTopMargin,size.width+2*KLeftMargin,size.height+2*KTopMargin);
}else{
self.bubbleImageV.frame = CGRectMake(CGRectGetMaxX(self.avateImageV.frame)+10,KTopMargin,size.width+2*KLeftMargin,size.height+2*KTopMargin);
}
bubbleView.frame = CGRectMake(KLeftMargin, KTopMargin, size.width, size.height);
break;
}
default:
break;
}
}
#import <UIKit/UIKit.h>
@interface BubbleView : UIView
@property(nonatomic,strong) UIImage *bubbleImage;
@property(nonatomic,assign) BOOL isSender;
- (void)setBubbleImage:(UIImage *)bubbleImage
isSender:(BOOL)isSender;
@end
#import "BubbleView.h"
#import "UIImage+Addition.h"
@implementation BubbleView
- (void)setBubbleImage:(UIImage *)bubbleImage isSender:(BOOL)isSender{
_bubbleImage = bubbleImage;
_isSender = isSender;
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect{
[UIImage drawImage:_bubbleImage atFrame:rect isSender:_isSender];
}
@end
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSInteger,MessageBubbleType){
MessageBubbleTypeText = 0, // 文本
MessageBubbleTypePhoto = 1, // 照片
MessageBubbleTypeVideo = 2, // 视频
MessageBubbleTypeVoice = 3, // 声音
MessageBubbleTypeLocation = 4 // 地理位置
};
@interface TalkMessage : NSObject
// 消息类型
@property (nonatomic,assign) MessageBubbleType messageBubbleType;
// 左右区别标示
@property (nonatomic,assign) bool flag;
// 文字的内容
@property (nonatomic,strong) NSString *talkContent;
@end
#import <UIKit/UIKit.h>
#import "TalkMessage.h"
@interface BubbleTextView : UIView
@property (nonatomic,strong) TalkMessage *message;
+ (instancetype)BubbleTextView;
@end
#import "BubbleTextView.h"
#define Kfont [UIFont systemFontOfSize:14]
@interface BubbleTextView ()
@property(nonatomic,strong) UILabel *textLabel;
@end
@implementation BubbleTextView
+ (instancetype)BubbleTextView
{
BubbleTextView *bubbleView = [[self alloc]init];
return bubbleView;
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.textLabel = [[UILabel alloc]initWithFrame:self.bounds];
self.textLabel.userInteractionEnabled = YES;
self.textLabel.font = Kfont;
self.textLabel.numberOfLines = 0;
self.textLabel.lineBreakMode = NSLineBreakByCharWrapping;
[self addSubview:self.textLabel];
}
return self;
}
- (void)setMessage:(TalkMessage *)message{
_message = message;
self.textLabel.text = message.talkContent;
}
- (void)layoutSubviews
{
[super layoutSubviews];
self.textLabel.frame = self.bounds;
}
@end
+ (void)drawImage:(UIImage *)image atFrame:(CGRect)rect isSender:(BOOL)isSender
{
CGFloat width = rect.size.width;
CGFloat height = rect.size.height;
UIBezierPath *path = [UIBezierPath bezierPath];
//左上弧度角
CGPoint leftTopCornerTopPoint = CGPointMake(KMargin+KCornRadius, KMargin);
CGPoint leftTopCornerBottomPoint = CGPointMake(KMargin, KMargin+KCornRadius);
//右上弧度角
CGPoint rightTopCornerTopPoint = CGPointMake(width-KCornRadius-KMargin, leftTopCornerTopPoint.y);
CGPoint rightTopCornerBottomPoint = CGPointMake(width-KMargin,leftTopCornerBottomPoint.y);
//左下弧度角
CGPoint leftBottomCornerTopPoint = CGPointMake(leftTopCornerBottomPoint.x, height-KMargin-KCornRadius);
CGPoint leftBottomCornerBottomPoint = CGPointMake(leftTopCornerTopPoint.x, height-KMargin);
//右下弧度角
CGPoint rightBottomCornerTopPoint = CGPointMake(rightTopCornerBottomPoint.x, leftBottomCornerTopPoint.y);
CGPoint rightBottomCornerBottomPoint = CGPointMake(rightTopCornerTopPoint.x, leftTopCornerBottomPoint.y);
if (isSender) {
//右上尖嘴符号:三角
//三角上端点
CGPoint triangleTopPoint = CGPointMake(rightTopCornerBottomPoint.x, rightTopCornerTopPoint.y+KTriangleSpace);
CGPoint triangleMiddlePoint = CGPointMake(width, triangleTopPoint.y+KTriangleWidth/2);
CGPoint trianglBottomPoint = CGPointMake(triangleTopPoint.x, triangleTopPoint.y+KTriangleWidth);
//先画左上圆弧
[path moveToPoint:leftTopCornerBottomPoint];
[path addArcWithCenter:CGPointMake(leftTopCornerTopPoint.x, leftTopCornerBottomPoint.y) radius:KCornRadius startAngle:-M_PI endAngle:-M_PI_2 clockwise:YES];
//上边框线
[path addLineToPoint:rightTopCornerTopPoint];
//右上圆弧
[path addArcWithCenter:CGPointMake(rightTopCornerTopPoint.x, rightTopCornerBottomPoint.y) radius:KCornRadius startAngle:-M_PI_2 endAngle:0 clockwise:YES];
//气泡尖嘴
[path addLineToPoint:triangleTopPoint];
[path addLineToPoint:triangleMiddlePoint];
[path addLineToPoint:trianglBottomPoint];
//右边框线
[path addLineToPoint:rightBottomCornerTopPoint];
//右下圆弧
[path addArcWithCenter:CGPointMake(rightBottomCornerBottomPoint.x, rightBottomCornerTopPoint.y) radius:KCornRadius startAngle:0 endAngle:M_PI_2 clockwise:YES];
//下边框线
[path addLineToPoint:leftBottomCornerBottomPoint];
[path addArcWithCenter:CGPointMake(leftBottomCornerBottomPoint.x, leftBottomCornerTopPoint.y) radius:KCornRadius startAngle:M_PI_2 endAngle:M_PI clockwise:YES];
}
else
{
//左上尖嘴符号:三角
//三角上端点
CGPoint triangleTopPoint = CGPointMake(leftTopCornerBottomPoint.x, leftTopCornerTopPoint.y+KTriangleSpace);
CGPoint triangleMiddlePoint = CGPointMake(0, triangleTopPoint.y+KTriangleWidth/2);
CGPoint trianglBottomPoint = CGPointMake(triangleTopPoint.x, triangleTopPoint.y+KTriangleWidth);
//先画左上圆弧
[path moveToPoint:leftTopCornerBottomPoint];
[path addArcWithCenter:CGPointMake(leftTopCornerTopPoint.x, leftTopCornerBottomPoint.y) radius:KCornRadius startAngle:-M_PI endAngle:-M_PI_2 clockwise:YES];
//上边框线
[path addLineToPoint:rightTopCornerTopPoint];
//右上圆弧
[path addArcWithCenter:CGPointMake(rightTopCornerTopPoint.x, rightTopCornerBottomPoint.y) radius:KCornRadius startAngle:-M_PI_2 endAngle:0 clockwise:YES];
//右边框线
[path addLineToPoint:rightBottomCornerTopPoint];
//右下圆弧
[path addArcWithCenter:CGPointMake(rightBottomCornerBottomPoint.x, rightBottomCornerTopPoint.y) radius:KCornRadius startAngle:0 endAngle:M_PI_2 clockwise:YES];
//下边框线
[path addLineToPoint:leftBottomCornerBottomPoint];
[path addArcWithCenter:CGPointMake(leftBottomCornerBottomPoint.x, leftBottomCornerTopPoint.y) radius:KCornRadius startAngle:M_PI_2 endAngle:M_PI clockwise:YES];
//气泡尖嘴
[path addLineToPoint:triangleTopPoint];
[path addLineToPoint:triangleMiddlePoint];
[path addLineToPoint:trianglBottomPoint];
}
//终于画完了,oh shit
[path addClip];
[image drawInRect:rect];
}
+ (UIImage *)imageWithColor:(UIColor *)color
{
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}