開發的朋友也許會常常遇到點擊輸入框激活出現鍵盤而致使輸入框被遮住的現象,經常使用的解決方案有兩種:ide
一、鍵盤出現的時候,將內容頁面適當上移動畫
二、鍵盤出現的時候,漂浮輸入框到適當位置 筆者認爲 第一種方案比較簡單,這裏只介紹第一種,第二種相似。server
1、首先對鍵盤事件進行監聽設置(可寫入viewDidLoad中):事件
//增長監聽,當鍵盤出現或改變時收出消息開發
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];hash
//增長監聽,當鍵退出時收出消息it
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];io
2、在監聽事件的兩個方法分別處理視圖的上移和下移,移動的距離可根據鍵盤的高度獲得 //實現當鍵盤出現的時候計算鍵盤的高度大小。用於輸入框顯示位置object
- (void)keyboardWillShow:(NSNotification*)aNotification { NSDictionary* info = [aNotification userInfo];select
//kbSize即為鍵盤尺寸 (有width, height)
CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
//獲得鍵盤的高度
keyboardhight=kbSize.height;
//將UISCROLLVIEW上移動 hashKeyBoard=YES;
//設置動畫的名字
[UIView beginAnimations:@"AnimationOpen" context:nil];
//設置動畫的間隔時間 [UIView setAnimationDuration:0.20];
//??使用當前正在運行的狀態開始下一段動畫
[UIView setAnimationBeginsFromCurrentState: YES];
//設置視圖移動的位移
self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y - keyboardhight, self.view.frame.size.width, self.view.frame.size.height);
//設置動畫結束 [UIView commitAnimations]; }
//下移就不贅述咯