簡體   English   中英

當鍵盤出現時使視圖可滾動

[英]Making the view scrollable when keyboard appears

設法在我的第一個視圖上得到它,但在第二個視圖上不起作用。

這是我在兩個視圖上所做的,在控制台中僅用於調試目的略有不同

-(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];
}

您正在注冊UIKeyboardDidShowNotificationUIKeyboardDidHideNotification通知,然后取消注冊UIKeyboardWillShowNotificationUIKeyboardWillHideNotification通知。 有你的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM