3 回答

TA貢獻1936條經驗 獲得超7個贊
采用
NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameEndUserInfoKey];

TA貢獻1848條經驗 獲得超2個贊
隨著iOS中自定義鍵盤的引入,這個問題變得更加復雜。
簡而言之,UIKeyboardWillShowNotification可以通過自定義鍵盤實現多次調用:
當蘋果的系統鍵盤被打開(縱向)
發送的UIKeyboardWillShowNotification的鍵盤高度為224
當了Swype鍵盤被打開(縱向):
發送的UIKeyboardWillShowNotification的鍵盤高度為0
發送的UIKeyboardWillShowNotification的鍵盤高度為216
發送的UIKeyboardWillShowNotification的鍵盤高度為256
當SwiftKey鍵盤被打開(縱向):
發送的UIKeyboardWillShowNotification的鍵盤高度為0
發送的UIKeyboardWillShowNotification的鍵盤高度為216
發送的UIKeyboardWillShowNotification的鍵盤高度為259
為了在一個代碼行中正確處理這些情況,您需要:
根據UIKeyboardWillShowNotification和UIKeyboardWillHideNotification通知注冊觀察者:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
創建一個全局變量以跟蹤當前的鍵盤高度:
CGFloat _currentKeyboardHeight = 0.0f;
實現keyboardWillShow以對鍵盤高度的當前變化做出反應:
- (void)keyboardWillShow:(NSNotification*)notification {
NSDictionary *info = [notification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
CGFloat deltaHeight = kbSize.height - _currentKeyboardHeight;
// Write code to adjust views accordingly using deltaHeight
_currentKeyboardHeight = kbSize.height;
}
注意:您可能希望為視圖的偏移設置動畫。該信息字典包含鍵的值UIKeyboardAnimationDurationUserInfoKey。此值可用于以與顯示鍵盤相同的速度為更改設置動畫。
將keyboardWillHide實現為reset _currentKeyboardHeight并對被關閉的鍵盤做出反應:
- (void)keyboardWillHide:(NSNotification*)notification {
NSDictionary *info = [notification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
// Write code to adjust views accordingly using kbSize.height
_currentKeyboardHeight = 0.0f;
}

TA貢獻1810條經驗 獲得超4個贊
在遇到這篇StackOverflow文章之前,我也遇到了這個問題:
轉換UIKeyboardFrameEndUserInfoKey
這將向您展示如何使用該convertRect功能,將鍵盤的大小轉換為可用的大小,但要以屏幕方向為準。
NSDictionary* d = [notification userInfo];
CGRect r = [d[UIKeyboardFrameEndUserInfoKey] CGRectValue];
r = [myView convertRect:r fromView:nil];
以前,我有一個iPad應用程序可以使用UIKeyboardFrameEndUserInfoKey但不使用convertRect,并且運行良好。
但是在iOS 8上,它不再能正常工作。突然,它報告說我的鍵盤在橫向模式下的iPad上運行,高度為1024像素。
因此,現在,在iOS 8上,必須使用此convertRect功能。
- 3 回答
- 0 關注
- 954 瀏覽
添加回答
舉報