如何防止键盘覆盖UITextView中的文本?

5

我在一个ViewController中有一个UITextView,它覆盖整个屏幕。但是当我在应用程序中输入文本时,如果我向下键入超过键盘的位置,则文本视图不会向上滚动。只有当我将光标键入到屏幕的最底部时,它才会向上滚动。但是,如果我在键盘所在位置之后继续键入,则TextView不会滚动,并且我正在输入的任何内容都会被隐藏起来。如何解决这个问题?


你尝试过在不输入时隐藏键盘吗? - Bruno Recillas
@BrunoRecillas 是的,但我希望在用户输入时,他们可以看到自己正在输入的内容,而不会被键盘挡住。 - PretentiousPanda
你在 StoryBoard 中为那个特定的 textView 启用了滚动吗? - Bruno Recillas
是的,textView 的滚动已启用。 - PretentiousPanda
你尝试过在输入时将TextView向上移动吗? - Mumthezir VP
3个回答

0

IQKeyboardManager 是专门为解决这个问题而构建的。它只需要一行代码:

IQKeyboardManager.sharedManager().enable = true

我强烈建议使用它,而不是开发自己的解决方案(虽然这是一个好的实践,但非常耗时)。


0
你可以改变TextView的框架,以便它不会在键盘下面。
你可以使用这段代码来响应键盘显示并获取键盘的大小。
[[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

}

0
你可以尝试这个。
以下是文本框的委托方法。
请确保在 .h 文件中包含了 。
- (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];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接