想在鍵盤上添加一個按鈕,實時根據鍵盤不同高度變換按鈕位置,再不做輸入的時候點擊按鈕能夠隱藏鍵盤,這種方式在很多軟件上都有體現,然后在網上查閱了關于檢測鍵盤高度一些相關知識,以下是一個Demo,代碼有很多需要優化地方,僅供需要者參考;
先看效果:




首先是我們在ViewDidLoada()中注冊了兩個通知,[NSNotificationCenterdefaultCenter],檢測鍵盤動態,一個是鍵盤將要彈出的時候,另一個是鍵盤將要退出時候鍵盤的信息
- (void)viewDidLoad
{
NSLog(@"%@",NSStringFromSelector(_cmd));
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
檢測鍵盤消息一個六種,根據字面意思差不多都能說明函數作用
UIKeyboardWillShowNotification 通知將要發布時候顯示鍵盤
UIKeyboardDidShowNotification 通知發布后立即顯示鍵盤
UIKeyboardWillHideNotification 通知發布前撤銷鍵盤
UIKeyboardDidHideNotification 通知發布后撤銷鍵盤
UIKeyboardWillChangeFrameNotification 通知發布前迅速變化的框架的鍵盤。
UIKeyboardDidChangeFrameNotification 通知發布后立即改變在鍵盤的框架。
NSLog(@"%@",NSStringFromSelector(_cmd));是我特意加上去的,它能在控制臺顯示打印出當前程序所調用的函數,我在下面每個函數都加了這一句,當我進行不同操作的時候,打印出被調用函數名,在調試程序時候比較適用吧;

注冊消息通知后,實現通知所響應的方法
- (void)handleKeyboardDidShow:(NSNotification *)notification
{
NSLog(@"%@",NSStringFromSelector(_cmd));
NSDictionary *info = [notification userInfo];
CGRect keyboardFrame;
[[info objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size;
CGFloat distanceToMove = kbSize.height;
NSLog(@"---->動態鍵盤高度:%f",distanceToMove);
if (exitButton == nil) {
exitButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
CGRect exitBtFrame = CGRectMake(self.view.frame.size.width-40, self.view.frame.size.height - distanceToMove, 40.0f, 30.0f);
exitButton.frame = exitBtFrame;
[exitButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateNormal];
[self.view addSubview:exitButton];
新聞熱點
疑難解答