我在一个ViewController中有一个UITextView,它覆盖整个屏幕。但是当我在应用程序中输入文本时,如果我向下键入超过键盘的位置,则文本视图不会向上滚动。只有当我将光标键入到屏幕的最底部时,它才会向上滚动。但是,如果我在键盘所在位置之后继续键入,则TextView不会滚动,并且我正在输入的任何内容都会被隐藏起来。如何解决这个问题?
我在一个ViewController中有一个UITextView,它覆盖整个屏幕。但是当我在应用程序中输入文本时,如果我向下键入超过键盘的位置,则文本视图不会向上滚动。只有当我将光标键入到屏幕的最底部时,它才会向上滚动。但是,如果我在键盘所在位置之后继续键入,则TextView不会滚动,并且我正在输入的任何内容都会被隐藏起来。如何解决这个问题?
IQKeyboardManager 是专门为解决这个问题而构建的。它只需要一行代码:
IQKeyboardManager.sharedManager().enable = true
我强烈建议使用它,而不是开发自己的解决方案(虽然这是一个好的实践,但非常耗时)。
[[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
}
- (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];
}