Move up keyboard when editing UITextField on iOS9

后端 未结 7 1381
太阳男子
太阳男子 2021-02-02 00:03

For my keyboards to move up to uncover UITextField in my iOS app, I used to implement this answer: https://stackoverflow.com/a/6908258/3855618 on iOS7 and 8 and it

7条回答
  •  梦如初夏
    2021-02-02 00:24

    We need to take keyboard frame from notification. When get reference of scrollView, tableView, etc. Convert low border of view to window`s coordinates. When determine how much keyboard covers our view, and if difference is greater than 0, we can add inset below. Try this code:

    - (void)subscribeKeyboardNotifications
    {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillShow:)
                                                     name:UIKeyboardWillShowNotification
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillHide:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];
    }
    
    - (void)unsubscribeKeyboardNotifications
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self
                                                        name:UIKeyboardWillShowNotification
                                                      object:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self
                                                        name:UIKeyboardWillHideNotification
                                                      object:nil];
    }
    
    
    - (void)keyboardWillShow:(NSNotification *)aNotification
    {
        CGRect keyBoardFrame = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
        UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
    
        UIScrollView *someScrollView = ......
    
        CGPoint tableViewBottomPoint = CGPointMake(0, CGRectGetMaxY([someScrollView bounds]));
        CGPoint convertedTableViewBottomPoint = [someScrollView convertPoint:tableViewBottomPoint
                                                                               toView:keyWindow];
    
        CGFloat keyboardOverlappedSpaceHeight = convertedTableViewBottomPoint.y - keyBoardFrame.origin.y;
    
        if (keyboardOverlappedSpaceHeight > 0)
        {
            UIEdgeInsets tableViewInsets = UIEdgeInsetsMake(0, 0, keyboardOverlappedSpaceHeight, 0);
            [someScrollView setContentInset:tableViewInsets];
        }
    }
    
    - (void)keyboardWillHide:(NSNotification *)aNotification
    {
        UIEdgeInsets tableViewInsets = UIEdgeInsetsZero;
        UIScrollView *someScrollView = ......
    
        [someScrollView setContentInset:tableViewInsets];
    }
    

提交回复
热议问题