【问题标题】:iOS keyboard obstructing the editing text in textviewiOS键盘阻碍了textview中的编辑文本
【发布时间】:2012-12-24 13:53:12
【问题描述】:

我正在我的 viewController 中实现一个 textView。这个 textView 覆盖了整个屏幕,因为我打算让这个视图让用户写下他们的笔记。但是,当用户触摸 textview 并弹出键盘时似乎存在问题。

问题是,一旦触摸 textview,键盘会显示一半的屏幕,而编辑文本的开头会隐藏在键盘后面。我尝试输入一些内容,但根本看不到文本,因为编辑文本位于键盘后面。有没有办法解决这个问题?

【问题讨论】:

  • 嗯,如何更改您的文本字段/文本视图的超级视图的“y”..

标签: ios keyboard textview uitextview


【解决方案1】:

在你的实现文件中编写 UITextView 的委托方法,并将你的 UITextView 的委托设置为 self

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    CGRect rect = txtMessage.frame;
    rect.size.height = 91;// you can set y position according to your convinience
    txtMessage.frame = rect;
    NSLog(@"texView frame is %@",NSStringFromCGRect(textView.frame));

    return YES;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    return YES;
}


- (void)textViewDidEndEditing:(UITextView *)textView{

    CGRect rect = txtMessage.frame;
    rect.size.height = 276; // set back orignal positions
    txtMessage.frame = rect;
   NSLog(@"EndTextView frame is %@",NSStringFromCGRect(textView.frame));

}

【讨论】:

  • 我认为应该有办法通过 Storyboard 解决这个问题。但是这段代码也很有魅力。无论如何,为什么我们这里需要 textFieldShouldEndEditing?
  • 当文本视图被要求退出第一响应者状态时调用此方法。如果编辑应该停止,则为YES,如果编辑会话应该继续,则为NO
  • 我在右上角实现了另一个完成按钮,让 textview 只需使用 [textView resign responder] 即可退出其第一响应者状态。这个按钮与 UITextViewDelegate 有什么关系?是否每次使用 UITextViewDelegate 时都需要显式实现这个函数?
  • 在这里阅读Apple documentation关于这个
【解决方案2】:

当键盘弹出时,您必须调整文本视图的大小。首先,定义一个新方法,为您的控制器注册键盘显示和隐藏通知:

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

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}

然后从您的viewDidLoad: 方法调用[self registerForKeyBoardNotifications];

之后,你必须实现回调方法:

这是keyboardWasShown:,您可以在其中获取键盘的高度并将该数量减去 textView 的框架高度(如您所说,您的文本视图会填满整个屏幕,因此最终高度是前一个高度减去键盘高度):

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGRect rect = self.textView.frame;
    rect.size.height -= kbSize.height;
}

这里是keyboardWillBeHidden:

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    CGRect rect = self.textView.frame;
    rect.size.height = SCREEN_HEIGHT;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    相关资源
    最近更新 更多