简体   繁体   中英

How can I prevent the keyboard from covering text in a UITextView?

I have a UITextView in a ViewController that covers the whole screen but when I run the app and am typing in it, if I type down past the keyboard then it won't scroll up. It will only scroll up if I type all the way down to the very bottom of the screen, but if I type past where the keyboard is then the TextView won't scroll and whatever I'm typing is hidden. How can I work around this?

You can change the frame of the textview so that it's not underneath the keyboard.

You can use this code to react to the keyboard being displayed and to get the size of the keyboard.

[[NSNotificationCenter defaultCenter] addObserver:self
                                 selector:@selector(keyboardWasShown:)
                                     name:UIKeyboardDidShowNotification
                                   object:nil];

- (void)keyboardWasShown:(NSNotification *)notification
{

 CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;


int height = MIN(keyboardSize.height,keyboardSize.width);
int width = MAX(keyboardSize.height,keyboardSize.width);

//Place code here to resize textview

}

You can try this

These are delegate methods for for textfield.

Please ensure you included <UITextFieldDelegate> in .h file.

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
}


- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self animateTextField: textField up: NO];
}

- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
    const int movementDistance = 80; // tweak as needed
    const float movementDuration = 0.3f; // tweak as needed

    int movement = (up ? -movementDistance : movementDistance);

    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}

IQKeyboardManager was built to created this exact problem. It requires just one line of code:

IQKeyboardManager.sharedManager().enable = true

I'd highly recommend using it instead of developing your own solution (albeit good practice, but extremely time-consuming).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM