iOS开发之微信聊天工具栏的封装

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

之前山寨了一个新浪微博(iOS开发之山寨版新浪微博小结),这几天就山寨个微信吧。之前已经把微信的视图结构简单的拖了一下(IOS开发之微信山寨版),今天就开始给微信加上具体的实现功能,那么就先从微信的聊天界面开始吧。提到封装是少不了写代码的,在封装组件的时候,为了组件的可移植性,我们就不能用storyboard来拖拽了。为了屏幕的适配,适应不同屏幕的手机,所以在封装组件的时候是少不了为我们的组件来添加约束。今天博客中的所有代码都是脱离storyboard的,这些代码在别的工程中也是可以使用的。好,废话少说,切入今天的正题。

微信大家基本上都用过,今天要做的就是微信的聊天工具条。聊天工具条还是比较复杂的,其中包括发送表情,发送文字,发送图片,发送声音,拍照等等功能,下面给出发送录音,文字,表情的代码,其他的和这几样类似。还是那句话百字不如一图,先来几张效果图吧。

在封装聊天工具条的的时候表情键盘是之前封装好的(请参考:“iOS开发之自定义表情键盘(组件封装与自动布局)”),所以拿过来就可以用的啦。因为不管是工具条还是表情键盘都是用约束来控件大小的,所以横屏也是没问题的,在大屏手机上也是没问题的。下面将会一步步讲解如何封装下面的聊天工具条。主要是对工具条的封装,表情键盘在这就不做讲解了。

一:ToolView预留的接口

在封装ToolView中主要用到Block回调,读者可以根据自己的个人习惯来选择是Block回调,还是委托回调或者是目标动作回调(笔者更喜欢Block回调),下面的代码是ToolView给调用者提供的接口

1//2//ToolView.h3//MecroMessage4//5//Created by (青玉伏案:博客地址(http://www.cnblogs.com/ludashi/)) on 14-9-22.6//Copyright (c) 2014年 Mrli. All rights reserved.7//89#import<UIKit/UIKit.h>101112//定义block类型把ToolView中TextView中的文字传入到Controller中13typedefvoid(^MyTextBlock) (NSString *myText);1415//录音时的音量16typedefvoid(^AudioVolumeBlock) (CGFloat volume);1718//录音存储地址19typedefvoid(^AudioURLBlock) (NSURL *audioURL);2021//改变根据文字改变TextView的高度22typedefvoid(^ContentSizeBlock)(CGSize contentSize);2324//录音取消的回调25typedefvoid(^CancelRecordBlock)(intflag);262728@interfaceToolView : UIView<UITextViewDelegate,AVAudioRecorderDelegate>293031//设置MyTextBlock32-(void) setMyTextBlock:(MyTextBlock)block;3334//设置声音回调35-(void) setAudioVolumeBlock:(AudioVolumeBlock) block;3637//设置录音地址回调38-(void) setAudioURLBlock:(AudioURLBlock) block;3940-(void)setContentSizeBlock:(ContentSizeBlock) block;4142-(void)setCancelRecordBlock:(CancelRecordBlock)block;4344-(void) changeFunctionHeight: (float) height;4546@end

View Code

二:初始化ToolView中所需的控件

1.为了更好的封装我们的组件,在.h中预留接口,在ToolView.m的延展中添加我们要使用的组件(私有属性),延展代码如下:

1@interfaceToolView()2//最左边发送语音的按钮3@PRoperty (nonatomic, strong) UIButton *voiceChangeButton;45//发送语音的按钮6@property (nonatomic, strong) UIButton *sendVoiceButton;78//文本视图9@property (nonatomic, strong) UITextView *sendTextView;1011//切换键盘12@property (nonatomic, strong) UIButton *changeKeyBoardButton;1314//More15@property (nonatomic, strong) UIButton *moreButton;1617//键盘坐标系的转换18@property (nonatomic, assign) CGRect endKeyBoardFrame;192021//表情键盘22@property (nonatomic, strong) FunctionView *functionView;2324//more25@property (nonatomic, strong) MoreView *moreView;2627//数据model28@property (strong, nonatomic) ImageModelClass *imageMode;2930@property (strong, nonatomic)HistoryImage *tempImage;313233//传输文字的block回调34@property (strong, nonatomic) MyTextBlock textBlock;3536//contentsinz37@property (strong, nonatomic) ContentSizeBlock sizeBlock;3839//传输volome的block回调40@property (strong, nonatomic) AudioVolumeBlock volumeBlock;4142//传输录音地址43@property (strong, nonatomic) AudioURLBlock urlBlock;4445//录音取消46@property (strong, nonatomic) CancelRecordBlock cancelBlock;474849//添加录音功能的属性50@property (strong, nonatomic) AVAudioRecorder *audioRecorder;5152@property (strong, nonatomic) NSTimer *timer;53@property (strong, nonatomic) NSURL *audioPlayURL;5455@end

View Code

2.接受相应的Block回调,把block传入ToolView中,代码如下:

1-(void)setMyTextBlock:(MyTextBlock)block2{3self.textBlock =block;4}56-(void)setAudioVolumeBlock:(AudioVolumeBlock)block7{8self.volumeBlock =block;9}1011-(void)setAudioURLBlock:(AudioURLBlock)block12{13self.urlBlock =block;14}1516-(void)setContentSizeBlock:(ContentSizeBlock)block17{18self.sizeBlock =block;19}2021-(void)setCancelRecordBlock:(CancelRecordBlock)block22{23self.cancelBlock =block;24}

View Code

3.控件的初始化,纯代码添加ToolView中要用到的组件(分配内存,配置相应的属性),因为是自定义组件的封装,所以我们的storyboard就用不上啦,添加控件的代码如下:

1//控件的初始化2-(void) addSubview3{4self.voiceChangeButton =[[UIButton alloc] initWithFrame:CGRectZero];5[self.voiceChangeButton setImage:[UIImage imageNamed:@"chat_bottom_voice_press.png"] forState:UIControlStateNormal];6[self.voiceChangeButton addTarget:self action:@selector(tapVoiceChangeButton:) forControlEvents:UIControlEventTouchUpInside];7[self addSubview:self.voiceChangeButton];89self.sendVoiceButton =[[UIButton alloc] initWithFrame:CGRectZero];10[self.sendVoiceButton setBackgroundImage:[UIImage imageNamed:@"chat_bottom_textfield.png"] forState:UIControlStateNormal];11[self.sendVoiceButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];12[self.sendVoiceButton setTitle:@"按住说话"forState:UIControlStateNormal];131415[self.sendVoiceButton addTarget:self action:@selector(tapSendVoiceButton:) forControlEvents:UIControlEventTouchUpInside];16self.sendVoiceButton.hidden =YES;17[self addSubview:self.sendVoiceButton];1819self.sendTextView =[[UITextView alloc] initWithFrame:CGRectZero];20self.sendTextView.delegate=self;21[self addSubview:self.sendTextView];2223self.changeKeyBoardButton =[[UIButton alloc] initWithFrame:CGRectZero];24[self.changeKeyBoardButton setImage:[UIImage imageNamed:@"chat_bottom_smile_nor.png"] forState:UIControlStateNormal];25[self.changeKeyBoardButton addTarget:self action:@selector(tapChangeKeyBoardButton:) forControlEvents:UIControlEventTouchUpInside];26[self addSubview:self.changeKeyBoardButton];2728self.moreButton =[[UIButton alloc] initWithFrame:CGRectZero];29[self.moreButton setImage:[UIImage imageNamed:@"chat_bottom_up_nor.png"] forState:UIControlStateNormal];30[self.moreButton addTarget:self action:@selector(tapMoreButton:) forControlEvents:UIControlEventTouchUpInside];31[self addSubview:self.moreButton];3233[self addDone];34353637//实例化FunctionView38self.functionView = [[FunctionView alloc] initWithFrame:CGRectMake(0,0,320,216)];39self.functionView.backgroundColor =[UIColor blackColor];4041//设置资源加载的文件名42self.functionView.plistFileName =@"emoticons";4344__weak __block ToolView *copy_self =self;45//获取图片并显示46[self.functionView setFunctionBlock:^(UIImage *image, NSString *imageText)47{48NSString *str = [NSString stringWithFormat:@"%@%@",copy_self.sendTextView.text, imageText];4950copy_self.sendTextView.text =str;5152//把使用过的图片存入sqlite53NSData *imageData =UIImagePNGRepresentation(image);54[copy_self.imageMode save:imageData ImageText:imageText];55}];565758//给sendTextView添加轻击手势59UITapGestureRecognizer *tapGesture =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];60[self.sendTextView addGestureRecognizer:tapGesture];616263//给sendVoiceButton添加长按手势64UILongPressGestureRecognizer *longPress =[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(sendVoiceButtonLongPress:)];65//设置长按时间66longPress.minimumPressDuration =0.2;67[self.sendVoiceButton addGestureRecognizer:longPress];6869//实例化MoreView70self.moreView = [[MoreView alloc] initWithFrame:CGRectMake(0,0,0,0)];71self.moreView.backgroundColor =[UIColor blackColor];72[self.moreView setMoreBlock:^(NSInteger index) {73NSLog(@"MoreIndex = %d",(int)index);74}];757677}

View Code

4.给我们的控件添加相应的约束,为了适合不同的屏幕,所以自动布局是少不了的。当然啦给控件添加约束也必须是手写代码啦,添加约束的代码如下:

1//给控件加约束2-(void)addConstraint3{4//给voicebutton添加约束5self.voiceChangeButton.translatesAutoresizingMaskIntoConstraints =NO;67NSArray *voiceConstraintH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[_voiceChangeButton(30)]"options:0metrics:0views:NSDictionaryOfVariableBindings(_voiceChangeButton)];8[self addConstraints:voiceConstraintH];910NSArray *voiceConstraintV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-8-[_voiceChangeButton(30)]"options:0metrics:0views:NSDictionaryOfVariableBindings(_voiceChangeButton)];11[self addConstraints:voiceConstraintV];12131415//给MoreButton添加约束16self.moreButton.translatesAutoresizingMaskIntoConstraints =NO;1718NSArray *moreButtonH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[_moreButton(30)]-5-|"options:0metrics:0views:NSDictionaryOfVariableBindings(_moreButton)];19[self addConstraints:moreButtonH];2021NSArray *moreButtonV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-8-[_moreButton(30)]"options:0metrics:0views:NSDictionaryOfVariableBindings(_moreButton)];22[self addConstraints:moreButtonV];232425//给changeKeyBoardButton添加约束26self.changeKeyBoardButton.translatesAutoresizingMaskIntoConstraints =NO;2728NSArray *changeKeyBoardButtonH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[_changeKeyBoardButton(33)]-43-|"options:0metrics:0views:NSDictionaryOfVariableBindings(_changeKeyBoardButton)];29[self addConstraints:changeKeyBoardButtonH];3031NSArray *changeKeyBoardButtonV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[_changeKeyBoardButton(33)]"options:0metrics:0views:NSDictionaryOfVariableBindings(_changeKeyBoardButton)];32[self addConstraints:changeKeyBoardButtonV];333435//给文本框添加约束36self.sendTextView.translatesAutoresizingMaskIntoConstraints =NO;37NSArray *sendTextViewConstraintH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-45-[_sendTextView]-80-|"options:0metrics:0views:NSDictionaryOfVariableBindings(_sendTextView)];38[self addConstraints:sendTextViewConstraintH];3940NSArray *sendTextViewConstraintV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[_sendTextView]-10-|"options:0metrics:0views:NSDictionaryOfVariableBindings(_sendTextView)];41[self addConstraints:sendTextViewConstraintV];424344//语音发送按钮45self.sendVoiceButton.translatesAutoresizingMaskIntoConstraints =NO;46NSArray *sendVoiceButtonConstraintH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-50-[_sendVoiceButton]-90-|"options:0metrics:0views:NSDictionaryOfVariableBindings(_sendVoiceButton)];47[self addConstraints:sendVoiceButtonConstraintH];4849NSArray *sendVoiceButtonConstraintV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-6-[_sendVoiceButton]-6-|"options:0metrics:0views:NSDictionaryOfVariableBindings(_sendVoiceButton)];50[self addConstraints:sendVoiceButtonConstraintV];515253}

View Code

5.因为我们要发送录音,所以对音频部分的初始化是少不了的,以下代码是对音频的初始化

1//录音部分初始化2-(void)audioInit3{4NSError * err =nil;56AVAudiosession*audioSession =[AVAudioSession sharedInstance];7[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];89if(err){10NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);11return;12}1314[audioSession setActive:YES error:&err];1516err =nil;17if(err){18NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);19return;20}2122//通过可变字典进行配置项的加载23NSMutableDictionary *setAudioDic =[[NSMutableDictionary alloc] init];2425//设置录音格式(aac格式)26[setAudioDic setValue:@(kAudioFormatMPEG4AAC) forKey:AVFormatIDKey];2728//设置录音采样率(Hz) 如:AVSampleRateKey==8000/44100/96000(影响音频的质量)29[setAudioDic setValue:@(44100) forKey:AVSampleRateKey];3031//设置录音通道数1 Or 232[setAudioDic setValue:@(1) forKey:AVNumberOfChannelsKey];3334//线性采样位数 8、16、24、3235[setAudioDic setValue:@16forKey:AVLinearPCMBitDepthKey];36//录音的质量37[setAudioDic setValue:@(AVAudioQualityHigh) forKey:AVEncoderAudioQualityKey];3839NSString *strUrl =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];4041NSString *fileName = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];424344NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@.aac", strUrl, fileName]];45_audioPlayURL =url;4647NSError *error;48//初始化49self.audioRecorder = [[AVAudioRecorder alloc]initWithURL:url settings:setAudioDic error:&error];50//开启音量检测51self.audioRecorder.meteringEnabled =YES;52self.audioRecorder.delegate=self;5354}

View Code

6.添加键盘回收键Done

1//给键盘添加done键2-(void) addDone3{4//TextView的键盘定制回收按钮5UIToolbar * toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0,0,320,30)];67UIBarButtonItem * item1 =[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(tapDone:)];8UIBarButtonItem * item2 =[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];9UIBarButtonItem * item3 =[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];10toolBar.items =@[item2,item1,item3];1112self.sendTextView.inputaccessoryView =toolBar;13}

View Code

三.编写控件的回调方法

控件添加好以后下面要添加触发控件要干的事情:

1.从最复杂的开始,长按发送录音的按钮时,会录音。松开收时会发送(在发送时要判断音频的时间,太小不允许发送)。录音时上滑取消录音(删除录音文件)。主要是给录音按钮加了一个LongPress手势,根据手势的状态来做不同的事情。关于手势的内容请参考之前的博客:(iOS开发之手势识别),下面是录音业务逻辑的实现(个人在Coding的时候,感觉这一块是工具条中最复杂的部分),代码如下:

1//长按手势触发的方法2-(void)sendVoiceButtonLongPress:(id)sender3{4staticinti =1;5if([sender isKindOfClass:[UILongPressGestureRecognizerclass]]) {67UILongPressGestureRecognizer * longPress =sender;89//录音开始10if(longPress.state ==UIGestureRecognizerStateBegan)11{1213i =1;1415[self.sendVoiceButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];16//录音初始化17[self audioInit];1819//创建录音文件,准备录音20if([self.audioRecorder prepareToRecord])21{22//开始23[self.audioRecorder record];2425//设置定时检测音量变化26_timer = [NSTimer scheduledTimerWithTimeInterval:0.05target:self selector:@selector(detectionVoice) userInfo:nil repeats:YES];27}28}293031//取消录音32if(longPress.state ==UIGestureRecognizerStateChanged)33{3435CGPoint piont =[longPress locationInView:self];36NSLog(@"%f",piont.y);3738if(piont.y < -20)39{40if(i ==1) {4142[self.sendVoiceButton setBackgroundImage:[UIImage imageNamed:@"chat_bottom_textfield.png"] forState:UIControlStateNormal];43[self.sendVoiceButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];44//删除录制文件45[self.audioRecorder deleteRecording];46[self.audioRecorder stop];47[_timer invalidate];4849UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示"message:@"录音取消"delegate:nil cancelButtonTitle:@"取消"otherButtonTitles: nil];50[alter show];51//去除图片用的52self.cancelBlock(1);53i =0;5455}565758}59}6061if(longPress.state ==UIGestureRecognizerStateEnded) {62if(i ==1)63{64NSLog(@"录音结束");65[self.sendVoiceButton setBackgroundImage:[UIImage imageNamed:@"chat_bottom_textfield.png"] forState:UIControlStateNormal];66[self.sendVoiceButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];6768doublecTime =self.audioRecorder.currentTime;69if(cTime >1)70{71//如果录制时间<2 不发送72NSLog(@"发出去");73self.urlBlock(self.audioPlayURL);74}75else76{77//删除记录的文件78[self.audioRecorder deleteRecording];79UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示"message:@"录音时间太短!"delegate:nil cancelButtonTitle:@"取消"otherButtonTitles: nil];80[alter show];81self.cancelBlock(1);8283}84[self.audioRecorder stop];85[_timer invalidate];86}87}888990}9192}

View Code

2.下面的代码是检测音量的变化,用于根据音量变化图片,代码如下:

1//录音的音量探测2- (void)detectionVoice3{4[self.audioRecorder updateMeters];//刷新音量数据5//获取音量的平均值 [recorder averagePowerForChannel:0];6//音量的最大值 [recorder peakPowerForChannel:0];78CGFloat lowPassResults = pow(10, (0.05* [self.audioRecorder peakPowerForChannel:0]));910//把声音的音量传给调用者11self.volumeBlock(lowPassResults);12}

View Code

3.轻击输入框时,切换到系统键盘,代码如下:

1//轻击sendText切换键盘2-(void)tapGesture:(UITapGestureRecognizer *) sender3{4if([self.sendTextView.inputView isEqual:self.functionView])5{6self.sendTextView.inputView =nil;78[self.changeKeyBoardButton setImage:[UIImage imageNamed:@"chat_bottom_smile_nor.png"] forState:UIControlStateNormal];910[self.sendTextView reloadInputViews];11}1213if(![self.sendTextView isFirstResponder])14{15[self.sendTextView becomeFirstResponder];16}17}

View Code

4.通过输入框的文字多少改变toolView的高度,因为输入框的约束是加在ToolView上的,所以需要把输入框的ContentSize通过block传到ToolView的调用者上,让ToolView的父视图来改变ToolView的高度,从而sendTextView的高度也会随着改变的,下面的代码是把ContentSize交给父视图:代码如下:

1//通过文字的多少改变toolView的高度2-(void)textViewDidChange:(UITextView *)textView3{4CGSize contentSize =self.sendTextView.contentSize;56self.sizeBlock(contentSize);7}

View Code

效果如下,文字多时TextView的高度也会增大:

5.点击最左边的按钮触发的事件(切换文本输入框和录音按钮),代码如下:

1//切换声音按键和文字输入框2-(void)tapVoiceChangeButton:(UIButton *) sender3{45if(self.sendVoiceButton.hidden ==YES)6{7self.sendTextView.hidden =YES;8self.sendVoiceButton.hidden =NO;9[self.voiceChangeButton setImage:[UIImage imageNamed:@"chat_bottom_keyboard_nor.png"] forState:UIControlStateNormal];1011if([self.sendTextView isFirstResponder]) {12[self.sendTextView resignFirstResponder];13}14}15else16{17self.sendTextView.hidden =NO;18self.sendVoiceButton.hidden =YES;19[self.voiceChangeButton setImage:[UIImage imageNamed:@"chat_bottom_voice_press.png"] forState:UIControlStateNormal];2021if(![self.sendTextView isFirstResponder]) {22[self.sendTextView becomeFirstResponder];23}24}25}

View Code

6.点击return发送文字(通过Block回调传入到父视图上),代码如下:

1//发送信息(点击return)2- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text3{4if([text isEqualToString:@"\n"])5{67//通过block回调把text的值传递到Controller中共8self.textBlock(self.sendTextView.text);910self.sendTextView.text =@"";1112returnNO;13}14returnYES;15}

View Code

7.录音按钮本身要做的事情(在LongPress没有被触发时调用)代码如下:

1//发送声音按钮回调的方法2-(void)tapSendVoiceButton:(UIButton *) sender3{4NSLog(@"sendVoiceButton");5//点击发送按钮没有触发长按手势要做的事儿6UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示"message:@"按住录音"delegate:nil cancelButtonTitle:@"取消"otherButtonTitles: nil];7[alter show];8}

View Code

8.调用表情键盘:

1//变成表情键盘2-(void)tapChangeKeyBoardButton:(UIButton *) sender3{4if([self.sendTextView.inputView isEqual:self.functionView])5{6self.sendTextView.inputView =nil;78[self.changeKeyBoardButton setImage:[UIImage imageNamed:@"chat_bottom_smile_nor.png"] forState:UIControlStateNormal];910[self.sendTextView reloadInputViews];11}12else13{14self.sendTextView.inputView =self.functionView;151617[self.changeKeyBoardButton setImage:[UIImage imageNamed:@"chat_bottom_keyboard_nor.png"] forState:UIControlStateNormal];1819[self.sendTextView reloadInputViews];20}2122if(![self.sendTextView isFirstResponder])23{24[self.sendTextView becomeFirstResponder];25}2627if(self.sendTextView.hidden ==YES) {28self.sendTextView.hidden =NO;29self.sendVoiceButton.hidden =YES;30[self.voiceChangeButton setImage:[UIImage imageNamed:@"chat_bottom_voice_press.png"] forState:UIControlStateNormal];3132}3334}

View Code

以上就是ToolView的所有封装代码,至于在Controller中如何使用他来发送消息,如何定义聊天Cell,如何处理录音文件,聊天时的气泡是如何实现的等功能,在以后的博客中会继续讲解,希望大家继续关注。(转载请注明出处)

Demo地址:https://github.com/lizelu/WeChat

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航