Move UIView up when the keyboard appears in iOS

后端 未结 18 1828
再見小時候
再見小時候 2020-11-28 20:38

I have a UIView, it is not inside UIScrollView. I would like to move up my View when the keyboard appears. Before I tried to use this solution: How can I make a UITextField

18条回答
  •  日久生厌
    2020-11-28 21:12

    try this one:-

     [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector (keyboardDidShow:)
                                                     name: UIKeyboardDidShowNotification object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector (keyboardDidHide:)
                                                     name: UIKeyboardDidHideNotification object:nil];
    
    -(void) keyboardDidShow: (NSNotification *)notif
        {
            CGSize keyboardSize = [[[notif userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
            UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height+[self getTableView].tableFooterView.frame.size.height, 0.0);
    
            [self getTableView].contentInset = contentInsets;
            [self getTableView].scrollIndicatorInsets = contentInsets;
    
            CGRect rect = self.frame; rect.size.height -= keyboardSize.height;
            if (!CGRectContainsPoint(rect, self.frame.origin))
            {
                CGPoint scrollPoint = CGPointMake(0.0, self.frame.origin.y - (keyboardSize.height - self.frame.size.height));
                [[self getTableView] setContentOffset:scrollPoint animated:YES];
            }
        }
    
    -(void) keyboardDidHide: (NSNotification *)notif
    {
        UIEdgeInsets contentInsets = UIEdgeInsetsZero;
        [self getTableView].contentInset = contentInsets;
        [self getTableView].scrollIndicatorInsets = contentInsets;
    }
    

提交回复
热议问题