我得到了一個UIViewController,我有一個UIScrollView裏面有幾個UITextFields。我從蘋果那裏得到了一段代碼,似乎是從鍵盤下面移動內容。保持從鍵盤下面的內容
- (void)keyboardWasShown:(NSNotification *)notification
{
// Step 1: Get the size of the keyboard.
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
// Step 2: Adjust the bottom content inset of your scroll view by the keyboard height.
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0);
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
// Step 3: Scroll the target text field into view.
CGRect aRect = self.view.frame;
aRect.size.height -= keyboardSize.height;
if (!CGRectContainsPoint(aRect, self.firstResponder.frame.origin)) {
CGPoint scrollPoint = CGPointMake(0.0, self.firstResponder.frame.origin.y - (keyboardSize.height-10));
[self.scrollView setContentOffset:scrollPoint animated:YES];
}
}
我的UIScrollView是320x416,因爲我有一個導航欄。此外,我的鍵盤獲得44個像素,因爲我正在添加一個UIToolBar,所以代碼並不真正起作用。我嘗試了各種配置來解決兩個問題:
- 最後兩個字段被UIToolBar +鍵盤覆蓋,但只有最後一個字段觸發UIScrollView移動。
- 除了UIScrollView在移動,由於UIToolBar,UITextField仍然在鍵盤後面。
UPDATE:這工作,但我敢肯定是錯誤的,如果是正確的,我不知道爲什麼,沒有對我來說很有意義。有人可以修復/解釋它嗎?
- (void)keyboardWasShown:(NSNotification *)notification
{
// Step 1: Get the size of the keyboard.
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
// Step 2: Adjust the bottom content inset of your scroll view by the keyboard height.
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height + 44.0f, 0.0);
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
// Step 3: Scroll the target text field into view.
CGRect aRect = self.view.frame;
aRect.size.height -= keyboardSize.height + 44.0f;
if (!CGRectContainsPoint(aRect, self.firstResponder.frame.origin)) {
CGPoint scrollPoint = CGPointMake(0.0, self.firstResponder.frame.origin.y - (keyboardSize.height-10.0f - 44.0f - 44.0f - 44.0f));
[self.scrollView setContentOffset:scrollPoint animated:YES];
}
}
UPDATE1:還有一個錯誤,我在UIToolBar先前的按鈕,如果我點擊最後一個文本框,滾動視圖上升,如果我搬回到第一文本視圖,它在視圖之外,因爲滾動視圖不會滾動。
第一行解決1.但第二個使得UIScrollView下降而不是上升。 – lolol
忘記了添加。改變這一點,CGPoint scrollPoint = CGPointMake(0.0,self.firstResponder.frame.origin.y - (keyboardSize.height-10 + 44.0f));如果仍然無法使用,請使用aRect.size.height = aRect.size.height - keyboardSize.height - 44.0f;部分。 – iDev
這兩種可能性都有問題,滾動視圖正在關閉。男人,我嘗試了很多東西。 – lolol