3 回答

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

TA貢獻1848條經(jīng)驗 獲得超2個贊
隨著iOS中自定義鍵盤的引入,這個問題變得更加復(fù)雜。
簡而言之,UIKeyboardWillShowNotification可以通過自定義鍵盤實現(xiàn)多次調(diào)用:
當(dāng)蘋果的系統(tǒng)鍵盤被打開(縱向)
發(fā)送的UIKeyboardWillShowNotification的鍵盤高度為224
當(dāng)了Swype鍵盤被打開(縱向):
發(fā)送的UIKeyboardWillShowNotification的鍵盤高度為0
發(fā)送的UIKeyboardWillShowNotification的鍵盤高度為216
發(fā)送的UIKeyboardWillShowNotification的鍵盤高度為256
當(dāng)SwiftKey鍵盤被打開(縱向):
發(fā)送的UIKeyboardWillShowNotification的鍵盤高度為0
發(fā)送的UIKeyboardWillShowNotification的鍵盤高度為216
發(fā)送的UIKeyboardWillShowNotification的鍵盤高度為259
為了在一個代碼行中正確處理這些情況,您需要:
根據(jù)UIKeyboardWillShowNotification和UIKeyboardWillHideNotification通知注冊觀察者:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
創(chuàng)建一個全局變量以跟蹤當(dāng)前的鍵盤高度:
CGFloat _currentKeyboardHeight = 0.0f;
實現(xiàn)keyboardWillShow以對鍵盤高度的當(dāng)前變化做出反應(yīng):
- (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;
}
注意:您可能希望為視圖的偏移設(shè)置動畫。該信息字典包含鍵的值UIKeyboardAnimationDurationUserInfoKey。此值可用于以與顯示鍵盤相同的速度為更改設(shè)置動畫。
將keyboardWillHide實現(xiàn)為reset _currentKeyboardHeight并對被關(guān)閉的鍵盤做出反應(yīng):
- (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條經(jīng)驗 獲得超4個贊
在遇到這篇StackOverflow文章之前,我也遇到了這個問題:
轉(zhuǎn)換UIKeyboardFrameEndUserInfoKey
這將向您展示如何使用該convertRect功能,將鍵盤的大小轉(zhuǎn)換為可用的大小,但要以屏幕方向為準(zhǔn)。
NSDictionary* d = [notification userInfo];
CGRect r = [d[UIKeyboardFrameEndUserInfoKey] CGRectValue];
r = [myView convertRect:r fromView:nil];
以前,我有一個iPad應(yīng)用程序可以使用UIKeyboardFrameEndUserInfoKey但不使用convertRect,并且運行良好。
但是在iOS 8上,它不再能正常工作。突然,它報告說我的鍵盤在橫向模式下的iPad上運行,高度為1024像素。
因此,現(xiàn)在,在iOS 8上,必須使用此convertRect功能。
- 3 回答
- 0 關(guān)注
- 959 瀏覽
添加回答
舉報