您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

動手封裝微信風格的聊天工具欄(iOS 實作)

編輯:iOS 開發綜合

微信幾乎人人都在用,這次我們就來複刻它的聊天工具欄。別看它只是一條細長的輸入區,背後其實同時牽涉到表情、文字、圖片、語音與拍照等多種輸入方式,邏輯密度遠比外觀看起來高得多。本文以「錄音發送、文字發送、表情切換」三條主線作為示範,其餘功能(拍照、選圖等)的實作思路與這幾項大同小異,讀通之後自行擴充即可。

先看一眼成品。工具欄裡的表情面板是先前已封裝完成的獨立元件,這裡直接拿來複用;由於工具欄與表情鍵盤的元件尺寸全部以 Auto Layout 約束描述,所以橫屏、豎屏乃至大屏機型都能自適應。以下分幾個步驟拆解 ToolView 的封裝過程,表情鍵盤本身不在本文討論範圍。

一、ToolView 對外暴露的介面

封裝時我主要採用 Block 回調,你也可以換成 delegate 或 target-action,純屬個人習慣。以下是 ToolView 提供給呼叫方的完整介面:

// ToolView.h
#import <UIKit/UIKit.h>

// 把 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>
- (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

二、內部控件的初始化

為了讓元件保持乾淨,.h 只暴露必要介面,真正要用的子元件全部寫進 ToolView.m 的 class extension 裡當私有屬性:

@interface ToolView()
@property (nonatomic, strong) UIButton *voiceChangeButton;   // 最左側:語音/鍵盤切換
@property (nonatomic, strong) UIButton *sendVoiceButton;     // 按住說話
@property (nonatomic, strong) UITextView *sendTextView;      // 文字輸入框
@property (nonatomic, strong) UIButton *changeKeyBoardButton;// 表情鍵盤切換
@property (nonatomic, strong) UIButton *moreButton;          // 更多
@property (nonatomic, assign) CGRect endKeyBoardFrame;
@property (nonatomic, strong) FunctionView *functionView;    // 表情鍵盤
@property (nonatomic, strong) MoreView *moreView;
@property (strong, nonatomic) ImageModelClass *imageMode;
@property (strong, nonatomic) HistoryImage *tempImage;
@property (strong, nonatomic) MyTextBlock textBlock;
@property (strong, nonatomic) ContentSizeBlock sizeBlock;
@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

接著把外部傳進來的 Block 存起來:

- (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; }

由於是自訂元件,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];

    // 表情鍵盤
    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;
        // 使用過的表情存進資料庫,方便日後做「最近使用」
        NSData *imageData = UIImagePNGRepresentation(image);
        [copy_self.imageMode save:imageData ImageText:imageText];
    }];

    // 點擊輸入框、長按說話
    UITapGestureRecognizer *tapGesture =
        [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
    [self.sendTextView addGestureRecognizer:tapGesture];

    UILongPressGestureRecognizer *longPress =
        [[UILongPressGestureRecognizer alloc] initWithTarget:self
                                                     action:@selector(sendVoiceButtonLongPress:)];
    longPress.minimumPressDuration = 0.2;
    [self.sendVoiceButton addGestureRecognizer:longPress];

    // 更多面板
    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);
    }];
}

約束同樣得手寫。用 Visual Format Language 描述雖然囉嗦,但換來的是任意屏幕尺寸下的穩定佈局:

- (void)addConstraint {
    self.voiceChangeButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[_voiceChangeButton(30)]"
                                                               options:0 metrics:0
                                                                 views:NSDictionaryOfVariableBindings(_voiceChangeButton)]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-8-[_voiceChangeButton(30)]"
                                                               options:0 metrics:0
                                                                 views:NSDictionaryOfVariableBindings(_voiceChangeButton)]];

    self.moreButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[_moreButton(30)]-5-|"
                                                               options:0 metrics:0
                                                                 views:NSDictionaryOfVariableBindings(_moreButton)]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-8-[_moreButton(30)]"
                                                               options:0 metrics:0
                                                                 views:NSDictionaryOfVariableBindings(_moreButton)]];

    self.changeKeyBoardButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[_changeKeyBoardButton(33)]-43-|"
                                                               options:0 metrics:0
                                                                 views:NSDictionaryOfVariableBindings(_changeKeyBoardButton)]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[_changeKeyBoardButton(33)]"
                                                               options:0 metrics:0
                                                                 views:NSDictionaryOfVariableBindings(_changeKeyBoardButton)]];

    self.sendTextView.translatesAutoresizingMaskIntoConstraints = NO;
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-45-[_sendTextView]-80-|"
                                                               options:0 metrics:0
                                                                 views:NSDictionaryOfVariableBindings(_sendTextView)]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[_sendTextView]-10-|"
                                                               options:0 metrics:0
                                                                 views:NSDictionaryOfVariableBindings(_sendTextView)]];

    self.sendVoiceButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-50-[_sendVoiceButton]-90-|"
                                                               options:0 metrics:0
                                                                 views:NSDictionaryOfVariableBindings(_sendVoiceButton)]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-6-[_sendVoiceButton]-6-|"
                                                               options:0 metrics:0
                                                                 views:NSDictionaryOfVariableBindings(_sendVoiceButton)]];
}

要錄音,音症患者般的 AVAudioSession 與 AVAudioRecorder 初始化躲不掉。這裡重點說明幾個關鍵參數:採樣率決定音質,通道數決定單聲道或立體聲,位深與編碼品質則影響檔案大小。

- (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];
    if (err) { NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]); return; }

    NSMutableDictionary *setAudioDic = [NSMutableDictionary dictionary];
    [setAudioDic setValue:@(kAudioFormatMPEG4AAC) forKey:AVFormatIDKey];   // aac 格式
    [setAudioDic setValue:@(44100) forKey:AVSampleRateKey];                 // 採樣率
    [setAudioDic setValue:@(1) forKey:AVNumberOfChannelsKey];               // 通道數
    [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;
}

最後幫鍵盤加一個「完成」工具列,避免使用者只能等著收起鍵盤:

- (void)addDone {
    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;
}

三、回呼方法:讓元件真正動起來

元件排好之後,接下來才是重頭戲。最複雜的一段是長按說話:按下開始錄音,手指上滑超過門檻則取消並刪檔,松手則結束錄音,同時還要判斷錄音時長是否過短而拒絕發送。這一切都靠 Long Press 手勢的 state 分流處理。

- (void)sendVoiceButtonLongPress:(id)sender {
    static int i = 1;
    if (![sender isKindOfClass:[UILongPressGestureRecognizer class]]) return;
    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];
        if (piont.y < -20 && i == 1) {   // 上滑超過 20pt 視為取消
            [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 && i == 1) {
        [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) {
            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];
    }
}

錄音過程中每 0.05 秒取一次音量,讓外層能畫出隨音量起伏的波形:

- (void)detectionVoice {
    [self.audioRecorder updateMeters];
    CGFloat lowPassResults = pow(10, (0.05 * [self.audioRecorder peakPowerForChannel:0]));
    self.volumeBlock(lowPassResults);
}

點一下輸入框,就從表情鍵盤切回系統鍵盤:

- (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];
    }
}

文字變多時,工具欄要能長高。由於輸入框的約束是掛在 ToolView 上的,所以把 contentSize 拋給呼叫方,由父視圖去調整 ToolView 的高度,輸入框自然就跟著變高:

- (void)textViewDidChange:(UITextView *)textView {
    CGSize contentSize = self.sendTextView.contentSize;
    self.sizeBlock(contentSize);
}

最左側的按鈕負責在「文字輸入」與「按住說話」之間切換,順帶處理第一回應者的交接:

- (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];
    }
}

按下 Return 就送出文字,並立刻清空輸入框:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
 replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        self.textBlock(self.sendTextView.text);
        self.sendTextView.text = @"";
        return NO;
    }
    return YES;
}

如果使用者只是輕點「按住說話」而沒有觸發長按手勢,就給個提示:

- (void)tapSendVoiceButton:(UIButton *)sender {
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"按住錄音"
                                                  delegate:nil cancelButtonTitle:@"取消"
                                        otherButtonTitles:nil];
    [alter show];
}

最後是表情鍵盤的呼出與收起。關鍵在於切換 inputView 之後記得呼叫 reloadInputViews,同時同步兩顆按鈕的圖示狀態:

- (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 怎麼定義、錄音檔如何上傳與播放、對話氣泡怎麼畫,還有更多可以聊的,留待後續文章再細說。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved