iOS键盘阻碍textview中的编辑文本

时间:2013-01-10 08:21:28

标签: ios keyboard textview uitextview

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

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

2 个答案:

答案 0 :(得分:2)

在实现文件中编写UITextView的委托方法,并将yout 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));

}

答案 1 :(得分: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;
}