天天看點

IOS學習-随着鍵盤高度變化自動調節界面内容

(網上摘抄并進行總結) 首先說明下鍵盤顯示消息和隐藏消息分别為:UIKeyboardWillShowNotification、UIKeyboardWillHideNotification;這個兩個消息系統會自動發送,前提是自己注冊接收此消息。 1、注冊鍵盤顯示消息通知: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; 2、注冊鍵盤隐藏消息通知: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; 3、鍵盤顯示的時候處理函數: -(void)keyboardWillShow:(NSNotification*)notif{     NSDictionary* userInfo=[notif userInfo];     NSValue* avalue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];     CGRect keyboardRect=[avalue CGRectValue];     int height=keyboardRect.size.height;//擷取鍵盤高度     } 4、鍵盤隐藏的時候處理函數: -(void)keyboardWillHide:(NSNotification*)notif{     } 5、移除注冊的鍵盤顯示和隐藏消息(放在dealloc中,軟體退出系統會自動調用): -(void)dealloc{     [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];     [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil]; }

總結:使用此方法非常靈活的根據鍵盤的變化調節界面的内容高度和大小,以前固定使用鍵盤高度216的時候,總會出現鍵盤高度和界面不能靈活搭配的情況,有時候使用216鍵盤高度可以讓界面和鍵盤之間銜接很正常,但是在使用不同類型鍵盤的時候發現鍵盤高度降低了,而我界面的高度調節的時候依然使用216鍵盤高度,這樣界面效果就很差,後來了解到内部消息機制來擷取鍵盤高度,使用後發現原先存在的問題都解決了。