2016-04-06 18 views
0

如果出現鍵盤,我想使視圖自動向上移動。已經使用蘋果的代碼here,它運作良好。自動移動UIScrollView區域的可見性

這就是我如何管理我的對象,所以我創建了UIScrollView,涵蓋了UIView。這UIViewUITextFieldUIButton組成。

Document Outline

這是我如何調整我的看法鍵盤出現時。

#pragma mark - Keyboard Handling 

// Call this method somewhere in your view controller setup code. 
- (void)registerForKeyboardNotifications 
{ 
    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(keyboardWasShown:) 
               name:UIKeyboardDidShowNotification object:nil]; 

    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(keyboardWillBeHidden:) 
               name:UIKeyboardWillHideNotification object:nil]; 

} 

// Called when the UIKeyboardDidShowNotification is sent. 
- (void)keyboardWasShown:(NSNotification*)aNotification 
{ 
    NSDictionary* info = [aNotification userInfo]; 
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; 

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0); 
    _scrollView.contentInset = contentInsets; 
    _scrollView.scrollIndicatorInsets = contentInsets; 

    // If active text field is hidden by keyboard, scroll it so it's visible 
    // Your app might not need or want this behavior. 
    CGRect aRect = self.view.frame; 
    aRect.size.height -= kbSize.height; 
    if (!CGRectContainsPoint(aRect, _mainView.frame.origin)) { 
     [self.scrollView scrollRectToVisible:_mainView.frame animated:YES]; 
    } 
} 

// Called when the UIKeyboardWillHideNotification is sent 
- (void)keyboardWillBeHidden:(NSNotification*)aNotification 
{ 
    UIEdgeInsets contentInsets = UIEdgeInsetsZero; 
    _scrollView.contentInset = contentInsets; 
    _scrollView.scrollIndicatorInsets = contentInsets; 
} 

但我認爲有一點讓這個奇怪。當鍵盤出現時,它會滾動並且我的UITextField變得可見。但我認爲這太緊張了。

Result

在我看來,這將是更好的,如果我的UITextField移動了一點點。我的問題是,我怎樣才能設置其滾動可見性?它看起來像一些變量應該有一些不斷被添加在這裏

CGRect aRect = self.view.frame; 
aRect.size.height -= kbSize.height; 
if (!CGRectContainsPoint(aRect, _mainView.frame.origin)) { 
    [self.scrollView scrollRectToVisible:_mainView.frame animated:YES]; 
} 

注意: 結果,我想 Expectation

謝謝你這麼多,一個小提示,將不勝感激。

回答

0

解決

我解決了這個由管理增加一些數量插頁內容。 在keyboardWasShown:中,我通過我的文本框和按鈕的高度添加了它的內容。假設它總共是100,所以就是這樣。

UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height+100, 0.0); 

非常感謝。

2

最簡單的解決方案是在鍵盤打開時移動視圖(或滾動視圖)。

- (void)keyboardWillShow:(NSNotification*)notification{ 
    [self.view setFrame:CGRectMake(0,-100, self.view.frame.size.width, self.view.frame.size.height)]; // where 100 is the offset 
    [self.view setNeedsDisplay]; 

} 

- (void)keyBoardWillHide:(NSNotification*)notification{ 
    [self.view setFrame:CGRectMake(0,0, self.view.frame.size.width, self.view.frame.size.height)]; 
    [self.view setNeedsDisplay]; 
}