Move UIView up when the keyboard appears in iOS

后端 未结 18 1816
再見小時候
再見小時候 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 20:47

    Declare a delegate, assign your text field to the delegate and then include these methods.

    Assuming you have a login form with email and password text fields, this code will fit perfectly:

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
        [self.emailTextField resignFirstResponder];
        [self.passwordTextField resignFirstResponder];
    
    }
    
    - (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
        if (self.emailTextField == textField) {
            [self.passwordTextField becomeFirstResponder];
        } else {
            [self.emailTextField resignFirstResponder];
            [self.passwordTextField resignFirstResponder];
        }
        return NO;
    }
    - (void)viewWillAppear:(BOOL)animated {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }
    
    - (void)viewWillDisappear:(BOOL)animated {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    }
    
    #pragma mark - keyboard movements
    - (void)keyboardWillShow:(NSNotification *)notification
    {
        CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
        [UIView animateWithDuration:0.3 animations:^{
            CGRect f = self.view.frame;
            f.origin.y = -0.5f * keyboardSize.height;
            self.view.frame = f;
        }];
    }
    
    -(void)keyboardWillHide:(NSNotification *)notification
    {
        [UIView animateWithDuration:0.3 animations:^{
            CGRect f = self.view.frame;
            f.origin.y = 0.0f;
            self.view.frame = f;
        }];
    }
    

提交回复
热议问题