Resize a view when a keyboard appears (iOS)

后端 未结 5 2007
轮回少年
轮回少年 2020-12-14 11:09

I realize there are many similar solutions, such as TPKeyboardAvoiding, Apple\'s famous solution, and various suggestions involving the use of UIScrollView. In my case, I ne

5条回答
  •  醉酒成梦
    2020-12-14 11:52

    Try this methods. Edit it according to your requirement.

    #define kOFFSET_FOR_KEYBOARD 280.0
    
    - (void)keyboardWillHide:(NSNotification *)notif {
        [self setViewMoveUp:NO];
    }
    
    
    - (void)keyboardWillShow:(NSNotification *)notif{
        [self setViewMoveUp:YES];
    }
    
    
    - (void)textFieldDidBeginEditing:(UITextField *)textField {
        stayup = YES;
        [self setViewMoveUp:YES];
    }
    
    
    - (void)textFieldDidEndEditing:(UITextField *)textField {
        stayup = NO;
        [self setViewMoveUp:NO];
    }
    
    //method to move the view up/down whenever the keyboard is shown/dismissed
    -(void)setViewMoveUp:(BOOL)moveUp
    {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3]; // if you want to slide up the view
        [UIView setAnimationBeginsFromCurrentState:YES];
    
        CGRect rect = self.view.frame;
        if (moveUp)
        {
            // 1. move the view's origin up so that the text field that will be hidden come above the keyboard 
            // 2. increase the size of the view so that the area behind the keyboard is covered up.
    
            if (rect.origin.y == 0 ) {
                rect.origin.y -= kOFFSET_FOR_KEYBOARD;
                //rect.size.height += kOFFSET_FOR_KEYBOARD;
            }
    
        }
        else
        {
            if (stayup == NO) {
                rect.origin.y += kOFFSET_FOR_KEYBOARD;
                //rect.size.height -= kOFFSET_FOR_KEYBOARD;
            }
        }
        self.view.frame = rect; 
        [UIView commitAnimations];
    }
    

提交回复
热议问题