微信年夜家根本上都用過,明天要做的就是微信的聊天對象條。聊天對象條照樣比擬龐雜的,個中包含發送臉色,發送文字,發送圖片,發送聲響,攝影等等功效,上面給動身送灌音,文字,臉色的代碼,其他的和這幾樣相似。照樣那句話百字不如一圖,先來幾張後果圖吧。

在封裝聊天對象條的的時刻臉色鍵盤是之前封裝好的,所以拿過去便可以用的啦。由於不論是對象條照樣臉色鍵盤都是用束縛來控件年夜小的,所以橫屏也是沒成績的,在年夜屏手機上也是沒成績的。上面將會一步步講授若何封裝上面的聊天對象條。重要是對對象條的封裝,臉色鍵盤在這就不做講授了。
1、ToolView預留的接口
在封裝ToolView中重要用到Block回調,讀者可以依據本身的小我習氣來選擇是Block回調,照樣拜托回調或許是目的舉措回調(筆者更愛好Block回調),上面的代碼是ToolView給挪用者供給的接口
// // ToolView.h // MecroMessage // // Created by (青玉伏案)on 14-9-22. // Copyright (c) 2014年 Mrli. All rights reserved. // #import <UIKit/UIKit.h> //界說block類型把ToolView中TextView中的文字傳入到Controller中 typedef void (^MyTextBlock) (NSString *myText); //灌音時的音量 typedef void (^AudioVolumeBlock) (CGFloat volume); //灌音存儲地址 typedef void (^AudioURLBlock) (NSURL *audioURL); //轉變依據文字轉變TextView的高度 typedef void (^ContentSizeBlock)(CGSize contentSize); //灌音撤消的回調 typedef void (^CancelRecordBlock)(int flag); @interface ToolView : UIView<UITextViewDelegate,AVAudioRecorderDelegate> //設置MyTextBlock -(void) setMyTextBlock:(MyTextBlock)block; //設置聲響回調 -(void) setAudioVolumeBlock:(AudioVolumeBlock) block; //設置灌音地址回調 -(void) setAudioURLBlock:(AudioURLBlock) block; -(void)setContentSizeBlock:(ContentSizeBlock) block; -(void)setCancelRecordBlock:(CancelRecordBlock)block; -(void) changeFunctionHeight: (float) height; @end
2、初始化ToolView中所需的控件
1.為了更好的封裝我們的組件,在.h中預留接口,在ToolView.m的延展中添加我們要應用的組件(公有屬性),延展代碼以下:
@interface ToolView() //最右邊發送語音的按鈕 @property (nonatomic, strong) UIButton *voiceChangeButton; //發送語音的按鈕 @property (nonatomic, strong) UIButton *sendVoiceButton; //文本視圖 @property (nonatomic, strong) UITextView *sendTextView; //切換鍵盤 @property (nonatomic, strong) UIButton *changeKeyBoardButton; //More @property (nonatomic, strong) UIButton *moreButton; //鍵盤坐標系的轉換 @property (nonatomic, assign) CGRect endKeyBoardFrame; //臉色鍵盤 @property (nonatomic, strong) FunctionView *functionView; //more @property (nonatomic, strong) MoreView *moreView; //數據model @property (strong, nonatomic) ImageModelClass *imageMode; @property (strong, nonatomic)HistoryImage *tempImage; //傳輸文字的block回調 @property (strong, nonatomic) MyTextBlock textBlock; //contentsinz @property (strong, nonatomic) ContentSizeBlock sizeBlock; //傳輸volome的block回調 @property (strong, nonatomic) AudioVolumeBlock volumeBlock; //傳輸灌音地址 @property (strong, nonatomic) AudioURLBlock urlBlock; //灌音撤消 @property (strong, nonatomic) CancelRecordBlock cancelBlock; //添加灌音功效的屬性 @property (strong, nonatomic) AVAudioRecorder *audioRecorder; @property (strong, nonatomic) NSTimer *timer; @property (strong, nonatomic) NSURL *audioPlayURL; @end
2.接收響應的Block回調,把block傳入ToolView中,代碼以下:
-(void)setMyTextBlock:(MyTextBlock)block
{
self.textBlock = block;
}
-(void)setAudioVolumeBlock:(AudioVolumeBlock)block
{
self.volumeBlock = block;
}
-(void)setAudioURLBlock:(AudioURLBlock)block
{
self.urlBlock = block;
}
-(void)setContentSizeBlock:(ContentSizeBlock)block
{
self.sizeBlock = block;
}
-(void)setCancelRecordBlock:(CancelRecordBlock)block
{
self.cancelBlock = block;
}
3.控件的初始化,純代碼添加ToolView中要用到的組件(分派內存,設置裝備擺設響應的屬性),由於是自界說組件的封裝,所以我們的storyboard就用不上啦,添加控件的代碼以下:
//控件的初始化
-(void) addSubview
{
self.voiceChangeButton = [[UIButton alloc] initWithFrame:CGRectZero];
[self.voiceChangeButton setImage:[UIImage imageNamed:@"chat_bottom_voice_press.png"] forState:UIControlStateNormal];
[self.voiceChangeButton addTarget:self action:@selector(tapVoiceChangeButton:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.voiceChangeButton];
self.sendVoiceButton = [[UIButton alloc] initWithFrame:CGRectZero];
[self.sendVoiceButton setBackgroundImage:[UIImage imageNamed:@"chat_bottom_textfield.png"] forState:UIControlStateNormal];
[self.sendVoiceButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.sendVoiceButton setTitle:@"按住措辭" forState:UIControlStateNormal];
[self.sendVoiceButton addTarget:self action:@selector(tapSendVoiceButton:) forControlEvents:UIControlEventTouchUpInside];
self.sendVoiceButton.hidden = YES;
[self addSubview:self.sendVoiceButton];
self.sendTextView = [[UITextView alloc] initWithFrame:CGRectZero];
self.sendTextView.delegate = self;
[self addSubview:self.sendTextView];
self.changeKeyBoardButton = [[UIButton alloc] initWithFrame:CGRectZero];
[self.changeKeyBoardButton setImage:[UIImage imageNamed:@"chat_bottom_smile_nor.png"] forState:UIControlStateNormal];
[self.changeKeyBoardButton addTarget:self action:@selector(tapChangeKeyBoardButton:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.changeKeyBoardButton];
self.moreButton = [[UIButton alloc] initWithFrame:CGRectZero];
[self.moreButton setImage:[UIImage imageNamed:@"chat_bottom_up_nor.png"] forState:UIControlStateNormal];
[self.moreButton addTarget:self action:@selector(tapMoreButton:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.moreButton];
[self addDone];
//實例化FunctionView
self.functionView = [[FunctionView alloc] initWithFrame:CGRectMake(0, 0, 320, 216)];
self.functionView.backgroundColor = [UIColor blackColor];
//設置資本加載的文件名
self.functionView.plistFileName = @"emoticons";
__weak __block ToolView *copy_self = self;
//獲得圖片並顯示
[self.functionView setFunctionBlock:^(UIImage *image, NSString *imageText)
{
NSString *str = [NSString stringWithFormat:@"%@%@",copy_self.sendTextView.text, imageText];
copy_self.sendTextView.text = str;
//把應用過的圖片存入SQLite
NSData *imageData = UIImagePNGRepresentation(image);
[copy_self.imageMode save:imageData ImageText:imageText];
}];
//給sendTextView添加輕擊手勢
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithtarget:self action:@selector(tapGesture:)];
[self.sendTextView addGestureRecognizer:tapGesture];
//給sendVoiceButton添加長按手勢
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithtarget:self action:@selector(sendVoiceButtonLongPress:)];
//設置長按時光
longPress.minimumPressDuration = 0.2;
[self.sendVoiceButton addGestureRecognizer:longPress];
//實例化MoreView
self.moreView = [[MoreView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
self.moreView.backgroundColor = [UIColor blackColor];
[self.moreView setMoreBlock:^(NSInteger index) {
NSLog(@"MoreIndex = %d",(int)index);
}];
}
4.給我們的控件添加響應的束縛,為了合適分歧的屏幕,所以主動結構是少不了的。固然啦給控件添加束縛也必需是手寫代碼啦,添加束縛的代碼以下:
//給控件加束縛
-(void)addConstraint
{
//給voicebutton添加束縛
self.voiceChangeButton.translatesAutoresizingMaskIntoConstraints = NO;
NSArray *voiceConstraintH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[_voiceChangeButton(30)]" options:0 metrics:0 views:NSDictionaryOfVariableBindings(_voiceChangeButton)];
[self addConstraints:voiceConstraintH];
NSArray *voiceConstraintV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-8-[_voiceChangeButton(30)]" options:0 metrics:0 views:NSDictionaryOfVariableBindings(_voiceChangeButton)];
[self addConstraints:voiceConstraintV];
//給MoreButton添加束縛
self.moreButton.translatesAutoresizingMaskIntoConstraints = NO;
NSArray *moreButtonH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[_moreButton(30)]-5-|" options:0 metrics:0 views:NSDictionaryOfVariableBindings(_moreButton)];
[self addConstraints:moreButtonH];
NSArray *moreButtonV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-8-[_moreButton(30)]" options:0 metrics:0 views:NSDictionaryOfVariableBindings(_moreButton)];
[self addConstraints:moreButtonV];
//給changeKeyBoardButton添加束縛
self.changeKeyBoardButton.translatesAutoresizingMaskIntoConstraints = NO;
NSArray *changeKeyBoardButtonH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[_changeKeyBoardButton(33)]-43-|" options:0 metrics:0 views:NSDictionaryOfVariableBindings(_changeKeyBoardButton)];
[self addConstraints:changeKeyBoardButtonH];
NSArray *changeKeyBoardButtonV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[_changeKeyBoardButton(33)]" options:0 metrics:0 views:NSDictionaryOfVariableBindings(_changeKeyBoardButton)];
[self addConstraints:changeKeyBoardButtonV];
//給文本框添加束縛
self.sendTextView.translatesAutoresizingMaskIntoConstraints = NO;
NSArray *sendTextViewConstraintH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-45-[_sendTextView]-80-|" options:0 metrics:0 views:NSDictionaryOfVariableBindings(_sendTextView)];
[self addConstraints:sendTextViewConstraintH];
NSArray *sendTextViewConstraintV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[_sendTextView]-10-|" options:0 metrics:0 views:NSDictionaryOfVariableBindings(_sendTextView)];
[self addConstraints:sendTextViewConstraintV];
//語音發送按鈕
self.sendVoiceButton.translatesAutoresizingMaskIntoConstraints = NO;
NSArray *sendVoiceButtonConstraintH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-50-[_sendVoiceButton]-90-|" options:0 metrics:0 views:NSDictionaryOfVariableBindings(_sendVoiceButton)];
[self addConstraints:sendVoiceButtonConstraintH];
NSArray *sendVoiceButtonConstraintV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-6-[_sendVoiceButton]-6-|" options:0 metrics:0 views:NSDictionaryOfVariableBindings(_sendVoiceButton)];
[self addConstraints:sendVoiceButtonConstraintV];
}
5.由於我們要發送灌音,所以對音頻部門的初始化是少不了的,以下代碼是對音頻的初始化
//灌音部門初始化
-(void)audioInit
{
NSError * err = nil;
AVAudIOSession *audIOSession = [AVAudIOSession sharedInstance];
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
if(err){
NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
return;
}
[audioSession setActive:YES error:&err];
err = nil;
if(err){
NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
return;
}
//經由過程可變字典停止設置裝備擺設項的加載
NSMutableDictionary *setAudioDic = [[NSMutableDictionary alloc] init];
//設置灌音格局(aac格局)
[setAudioDic setValue:@(kAudioFormatMPEG4AAC) forKey:AVFormatIDKey];
//設置灌音采樣率(Hz) 如:AVSampleRateKey==8000/44100/96000(影響音頻的質量)
[setAudioDic setValue:@(44100) forKey:AVSampleRateKey];
//設置灌音通道數1 Or 2
[setAudioDic setValue:@(1) forKey:AVNumberOfChannelsKey];
//線性采樣位數 8、16、24、32
[setAudioDic setValue:@16 forKey:AVLinearPCMBitDepthKey];
//灌音的質量
[setAudioDic setValue:@(AVAudioQualityHigh) forKey:AVEncoderAudioQualityKey];
NSString *strUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *fileName = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@.aac", strUrl, fileName]];
_audioPlayURL = url;
NSError *error;
//初始化
self.audioRecorder = [[AVAudioRecorder alloc]initWithURL:url settings:setAudioDic error:&error];
//開啟音量檢測
self.audioRecorder.meteringEnabled = YES;
self.audioRecorder.delegate = self;
}
6.添加鍵盤收受接管鍵Done
//給鍵盤添加done鍵
-(void) addDone
{
//TextView的鍵盤定制收受接管按鈕
UIToolbar * toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
UIBarButtonItem * item1 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(tapDone:)];
UIBarButtonItem * item2 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem * item3 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
toolBar.items = @[item2,item1,item3];
self.sendTextView.inputAccessoryView =toolBar;
}
三.編寫控件的回調辦法
控件添加好今後上面要添加觸發控件要干的工作:
1.從最龐雜的開端,長按發送灌音的按鈕時,會灌音。松開收時會發送(在發送時要斷定音頻的時光,太小不許可發送)。灌音時上滑撤消灌音(刪除灌音文件)。重要是給灌音按鈕加了一個LongPress手勢,依據手勢的狀況來做分歧的工作。關於手勢的內容請參考之前的博客:(iOS開辟之手勢辨認),上面是灌音營業邏輯的完成(小我在Coding的時刻,感到這一塊是對象條中最龐雜的部門),代碼以下:
//長按手勢觸發的辦法
-(void)sendVoiceButtonLongPress:(id)sender
{
static int i = 1;
if ([sender isKindOfClass:[UILongPressGestureRecognizer class]]) {
UILongPressGestureRecognizer * longPress = sender;
//灌音開端
if (longPress.state == UIGestureRecognizerStateBegan)
{
i = 1;
[self.sendVoiceButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//灌音初始化
[self audioInit];
//創立灌音文件,預備灌音
if ([self.audioRecorder prepareToRecord])
{
//開端
[self.audioRecorder record];
//設置准時檢測音質變化
_timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(detectionVoice) userInfo:nil repeats:YES];
}
}
//撤消灌音
if (longPress.state == UIGestureRecognizerStateChanged)
{
CGPoint piont = [longPress locationInView:self];
NSLog(@"%f",piont.y);
if (piont.y < -20)
{
if (i == 1) {
[self.sendVoiceButton setBackgroundImage:[UIImage imageNamed:@"chat_bottom_textfield.png"] forState:UIControlStateNormal];
[self.sendVoiceButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//刪除錄制文件
[self.audioRecorder deleteRecording];
[self.audioRecorder stop];
[_timer invalidate];
UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"灌音撤消" delegate:nil cancelButtonTitle:@"撤消" otherButtonTitles: nil];
[alter show];
//去除圖片用的
self.cancelBlock(1);
i = 0;
}
}
}
if (longPress.state == UIGestureRecognizerStateEnded) {
if (i == 1)
{
NSLog(@"灌音停止");
[self.sendVoiceButton setBackgroundImage:[UIImage imageNamed:@"chat_bottom_textfield.png"] forState:UIControlStateNormal];
[self.sendVoiceButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
double cTime = self.audioRecorder.currentTime;
if (cTime > 1)
{
//假如錄制時光<2 不發送
NSLog(@"收回去");
self.urlBlock(self.audioPlayURL);
}
else
{
//刪除記載的文件
[self.audioRecorder deleteRecording];
UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"灌音時光太短!" delegate:nil cancelButtonTitle:@"撤消" otherButtonTitles: nil];
[alter show];
self.cancelBlock(1);
}
[self.audioRecorder stop];
[_timer invalidate];
}
}
}
}
2.上面的代碼是檢測音量的變更,用於依據音質變化圖片,代碼以下:
//灌音的音量探測
- (void)detectionVoice
{
[self.audioRecorder updateMeters];//刷新音量數據
//獲得音量的均勻值 [recorder averagePowerForChannel:0];
//音量的最年夜值 [recorder peakPowerForChannel:0];
CGFloat lowPassResults = pow(10, (0.05 * [self.audioRecorder peakPowerForChannel:0]));
//把聲響的音量傳給挪用者
self.volumeBlock(lowPassResults);
}
3.輕擊輸出框時,切換到體系鍵盤,代碼以下:
//輕擊sendText切換鍵盤
-(void)tapGesture:(UITapGestureRecognizer *) sender
{
if ([self.sendTextView.inputView isEqual:self.functionView])
{
self.sendTextView.inputView = nil;
[self.changeKeyBoardButton setImage:[UIImage imageNamed:@"chat_bottom_smile_nor.png"] forState:UIControlStateNormal];
[self.sendTextView reloadInputViews];
}
if (![self.sendTextView isFirstResponder])
{
[self.sendTextView becomeFirstResponder];
}
}
4.經由過程輸出框的文字若干轉變toolView的高度,由於輸出框的束縛是加在ToolView上的,所以須要把輸出框的ContentSize經由過程block傳到ToolView的挪用者上,讓ToolView的父視圖來轉變ToolView的高度,從而sendTextView的高度也會跟著轉變的,上面的代碼是把ContentSize交給父視圖:代碼以下:
//經由過程文字的若干轉變toolView的高度
-(void)textViewDidChange:(UITextView *)textView
{
CGSize contentSize = self.sendTextView.contentSize;
self.sizeBlock(contentSize);
}
後果以下,文字多時TextView的高度也會增年夜:

5.點擊最右邊的按鈕觸發的事宜(切換文本輸出框和灌音按鈕),代碼以下:
//切換聲響按鍵和文字輸出框
-(void)tapVoiceChangeButton:(UIButton *) sender
{
if (self.sendVoiceButton.hidden == YES)
{
self.sendTextView.hidden = YES;
self.sendVoiceButton.hidden = NO;
[self.voiceChangeButton setImage:[UIImage imageNamed:@"chat_bottom_keyboard_nor.png"] forState:UIControlStateNormal];
if ([self.sendTextView isFirstResponder]) {
[self.sendTextView resignFirstResponder];
}
}
else
{
self.sendTextView.hidden = NO;
self.sendVoiceButton.hidden = YES;
[self.voiceChangeButton setImage:[UIImage imageNamed:@"chat_bottom_voice_press.png"] forState:UIControlStateNormal];
if (![self.sendTextView isFirstResponder]) {
[self.sendTextView becomeFirstResponder];
}
}
}
6.點擊return發送文字(經由過程Block回調傳入到父視圖上),代碼以下:
//發送信息(點擊return)
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if ([text isEqualToString:@"\n"])
{
//經由過程block回調把text的值傳遞到Controller中共
self.textBlock(self.sendTextView.text);
self.sendTextView.text = @"";
return NO;
}
return YES;
}
7.灌音按鈕自己要做的工作(在LongPress沒有被觸發時挪用)代碼以下:
//發送聲響按鈕回調的辦法
-(void)tapSendVoiceButton:(UIButton *) sender
{
NSLog(@"sendVoiceButton");
//點擊發送按鈕沒有觸發長按手勢要做的事兒
UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"按住灌音" delegate:nil cancelButtonTitle:@"撤消" otherButtonTitles: nil];
[alter show];
}
8.挪用臉色鍵盤:
//釀成臉色鍵盤
-(void)tapChangeKeyBoardButton:(UIButton *) sender
{
if ([self.sendTextView.inputView isEqual:self.functionView])
{
self.sendTextView.inputView = nil;
[self.changeKeyBoardButton setImage:[UIImage imageNamed:@"chat_bottom_smile_nor.png"] forState:UIControlStateNormal];
[self.sendTextView reloadInputViews];
}
else
{
self.sendTextView.inputView = self.functionView;
[self.changeKeyBoardButton setImage:[UIImage imageNamed:@"chat_bottom_keyboard_nor.png"] forState:UIControlStateNormal];
[self.sendTextView reloadInputViews];
}
if (![self.sendTextView isFirstResponder])
{
[self.sendTextView becomeFirstResponder];
}
if (self.sendTextView.hidden == YES) {
self.sendTextView.hidden = NO;
self.sendVoiceButton.hidden = YES;
[self.voiceChangeButton setImage:[UIImage imageNamed:@"chat_bottom_voice_press.png"] forState:UIControlStateNormal];
}
}
以上就是ToolView的一切封裝代碼,至於在Controller中若何應用他來發送新聞,若何界說聊天Cell,若何處置灌音文件,聊地利的氣泡是若何完成的等功效,在今後的文章中會持續講授,願望年夜家持續存眷。
【iOS開辟之微信聊天對象欄的封裝】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!