1. 程式人生 > >iOS中處理鍵盤彈出時,scrollview或者tableview的調整

iOS中處理鍵盤彈出時,scrollview或者tableview的調整

http://www.cnblogs.com/dcty/archive/2012/03/11/2390403.html

以前的做法和這個比起來簡直就是xxxx,今天看官方的參考庫又學了一招~

以前的實現效果和這個是一樣,不過程式碼上比這個多了點

程式清單5-1  處理鍵盤通告

// 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(keyboardWasHidden:)
            name:UIKeyboardDidHideNotification object:nil];
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    if (keyboardShown)
        return;
    NSDictionary* info = [aNotification userInfo];
    // Get the size of the keyboard.
    NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
    CGSize keyboardSize = [aValue CGRectValue].size;
    // Resize the scroll view (which is the root view of the window)
    CGRect viewFrame = [scrollView frame];
    viewFrame.size.height -= keyboardSize.height;
    scrollView.frame = viewFrame;
    // Scroll the active text field into view.
    CGRect textFieldRect = [activeField frame];
    [scrollView scrollRectToVisible:textFieldRect animated:YES];
    keyboardShown = YES;
}
// Called when the UIKeyboardDidHideNotification is sent
- (void)keyboardWasHidden:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    // Get the size of the keyboard.
    NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
    CGSize keyboardSize = [aValue CGRectValue].size;
    // Reset the height of the scroll view to its original value
    CGRect viewFrame = [scrollView frame];
    viewFrame.size.height += keyboardSize.height;
    scrollView.frame = viewFrame;
    keyboardShown = NO;
}

上面程式清單中的keyboardShown變數是一個布林值,用於跟蹤鍵盤是否可見。如果您的使用者介面有多個文字輸入框,則使用者可能觸擊其中的任意一個進行編輯。發生這種情況時,雖然鍵盤並不消失,但是每次開始編輯新的文字框時,系統都會產生UIKeyboardDidShowNotification通告。您可以通過跟蹤鍵盤是否確實被隱藏來避免多次減少滾動檢視的尺寸。

程式清單5-2顯示了一些額外的程式碼,檢視控制器用這些程式碼來設定和清理之前例子中的activeField變數。在初始化時,介面中的每個文字框都將檢視控制器設定為自己的委託。因此,當文字編輯框被啟用的時候,這些方法就會被呼叫。更多關於文字框及其委託通告的資訊,請參見。

程式清單5-2  跟蹤活動文字框的方法

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    activeField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    activeField = nil;
}