Move UIView up when the keyboard appears in iOS

后端 未结 18 1824
再見小時候
再見小時候 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:04

    I found theDuncs answer very useful and below you can find my own (refactored) version:


    Main Changes

    1. Now getting the keyboard size dynamically, rather than hard coding values
    2. Extracted the UIView Animation out into it's own method to prevent duplicate code
    3. Allowed duration to be passed into the method, rather than being hard coded

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

    - (void)keyboardWillShow:(NSNotification *)notification {
        CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    
        float newVerticalPosition = -keyboardSize.height;
    
        [self moveFrameToVerticalPosition:newVerticalPosition forDuration:0.3f];
    }
    
    
    - (void)keyboardWillHide:(NSNotification *)notification {
        [self moveFrameToVerticalPosition:0.0f forDuration:0.3f];
    }
    
    
    - (void)moveFrameToVerticalPosition:(float)position forDuration:(float)duration {
        CGRect frame = self.view.frame;
        frame.origin.y = position;
    
        [UIView animateWithDuration:duration animations:^{
            self.view.frame = frame;
        }];
    }
    

提交回复
热议问题