IM聊天頁面監聽鍵盤的彈出,聊天視圖跟隨鍵盤上移
-
由于鍵盤彈出的時候是用到了通知,所以我們先來看看通知的用法:
-
先創建兩個類: LHLPerson 和 LHLZhaoPin ,我們想要實現招聘類去 NSNotificationCenter 發布通知,在發布之前Person類要監聽通知.
- ViewController.m 中:
// // ViewController.m // 通知練習 // // Created by admin on 16/11/4. // Copyright ? 2016年 冷洪林. All rights reserved. //
import "ViewController.h"
import "LHLPerson.h"
import "LHLZhaoPin.h"
@interface ViewController ()
@end
@implementation ViewController
(void)viewDidLoad { [super viewDidLoad];
// 初始化三個Person類 LHLPerson *p1 = [[LHLPerson alloc] init];
// 初始化兩個公司 LHLZhaoPin *tencent = [[LHLZhaoPin alloc] init];
// 獲取通知中心(單例) NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
// 監聽通知(注意:監聽一定要在注冊之前,通俗的解釋就是好比別人放屁,放完了再去肯定已經沒有了,要在放之前就湊過去,哈哈哈 有點小邪惡) /**
- @param addObserver : 通知的監聽者
- @param SEL : 監聽到通知后觸發監聽者的哪個方法
- @param name : 監聽通知的名稱 如果為nil,則不限制
@param object : 監聽哪個對象的通知 如果為nil,則不限制 / [center addObserver:p1 selector:@selector(oneNoti:) name:@"tencentNoti" object:nil];
// 發布 [center postNotificationName:@"tencentNoti"
object:tencent userInfo:@{ @"title" : @"招聘前臺" }];
} // 移除通知 [center removeObserver:p1]; // 移除p1所有的通知
@end</code></pre>
- LHLPerson.h 中:
// // LHLPerson.m // 通知練習 // // Created by admin on 16/11/4. // Copyright ? 2016年 冷洪林. All rights reserved. //
import "LHLPerson.h"
@implementation LHLPerson
- (void)oneNoti:(NSNotification *)noti { NSLog(@"%@", noti); }
@end</code></pre>
-
程序運行效果
好了,通知的基本用法已經搞定,接下來我們切回主題,監聽鍵盤的彈出,聊天視圖跟隨鍵盤上移:
-
在開始之前我們先設置一下鍵盤的退出,在這里是在開始拖拽tableView的時候彈出鍵盤
// 拖拽tableView的時候彈出鍵盤
- (void)scrollViewWillBeginDragging:(UIScrollView )scrollView
{
[self.view endEditing:YES];
}</code></pre>
- viewDidLoad 方法:
// 監聽鍵盤彈出的通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
-
實現 keyboardWillChangeFrame: 方法并打印傳過來的 NSNotification :
- (void)keyboardWillChangeFrame:(NSNotification
-
可以看到,在鍵盤彈出和退出時,都監聽到了一次通知,我們需要用的是 UIKeyboardFrameEndUserInfoKey :
-
下面就該移動view的位置了,其實整個過程是這樣的:鍵盤的視圖是隱藏在view的最底部,當調用鍵盤的時候它就會立即從下面彈出,此時我們的view也跟隨鍵盤整體向上移動.
-
利用transform來改變view的frame:
- (void)keyboardWillChangeFrame:(NSNotification *)noti { CGRect keyboardFrame = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; self.view.transform = CGAffineTransformMakeTranslation(0, keyboardFrame.origin.y - LHLScreenH); }
-
到這里我們的目的也就達到了:
來自:http://www.jianshu.com/p/a19e7fb3c63f
-