3

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

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

4

2 回答 2

2

在您的实现文件中编写 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));

}
于 2013-01-10T08:31:13.133 回答
0

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

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

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

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

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

在这里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;
}
于 2013-01-10T08:53:36.180 回答