出现键盘时使视图可滚动

问题描述

| 设法在我的第一个视图上获得它,但在第二个视图上不起作用。 这是我在两种视图上所做的工作,在控制台中出于调试目的仅稍有不同
-(void) viewWillAppear:(BOOL)animated {
    //---registers the notifications for keyboard---
    // to see if keyboard is shown / not shown
    [[NSNotificationCenter defaultCenter]
     addobserver: self
     selector:@selector(keyboardDidShow:)
     name:UIKeyboardDidShowNotification
     object:self.view.window];

    [[NSNotificationCenter defaultCenter]
     addobserver:self
     selector:@selector(keyboardDidHide:)
     name:UIKeyboardDidHideNotification
     object:nil];
}

//---when the keyboard appears---
-(void) keyboardDidShow:(NSNotification *) notification {
    if (keyboardisShown) return;
    NSLog(@\"Keyboard is visible 1\"); // debugger purpose \"Keyboard is visible 2\" on the second view.

    NSDictionary* info = [notification userInfo];

    //---obtain the size of the keyboard---
    NSValue *aValue =
    [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect =
    [self.view convertRect:[aValue CGRectValue] fromView:nil];


    //---resize the scroll view (with keyboard)---
    CGRect viewFrame = [scrollview frame];
    NSLog(@\"%f\",viewFrame.size.height);
    viewFrame.size.height -= keyboardRect.size.height;
    scrollview.frame = viewFrame;
    NSLog(@\"%f\",keyboardRect.size.height);
    NSLog(@\"%f\",viewFrame.size.height);
    //---scroll to the current text field---
     CGRect textFieldRect = [currentTextField frame];
    [scrollview scrollRectToVisible:textFieldRect animated:YES];
    keyboardisShown = YES;
}

//---when the keyboard disappears---
-(void) keyboardDidHide:(NSNotification *) notification {
    NSDictionary* info = [notification userInfo];

    //---obtain the size of the keyboard---
    NSValue* aValue =
    [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect =
    [self.view convertRect:[aValue CGRectValue] fromView:nil];


    //---resize the scroll view back to the original size
    // (without keyboard)---
    CGRect viewFrame = [scrollview frame];
    viewFrame.size.height += keyboardRect.size.height;
    scrollview.frame = viewFrame;

    keyboardisShown = NO;
}

//---before the View window disappear---
-(void) viewWilldisappear:(BOOL)animated {
    //---removes the notifications for keyboard---
    [[NSNotificationCenter defaultCenter]
     removeObserver: self
     name:UIKeyboardWillShowNotification
     object:nil];

    [[NSNotificationCenter defaultCenter]
     removeObserver:self
     name:UIKeyboardWillHideNotification
     object:nil];
}
    

解决方法

您正在注册
UIKeyboardDidShowNotification
UIKeyboardDidHideNotification
通知,然后注销
UIKeyboardWillShowNotification
UIKeyboardWillHideNotification
通知。这是您的错误。