美文网首页
scrollView中textView键盘遮挡问题处理

scrollView中textView键盘遮挡问题处理

作者: 向晚forever | 来源:发表于2017-01-06 18:05 被阅读63次

在viewDidLoad里面创建两个监听键盘出来和隐藏的通知

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:@"UIKeyboardWillShowNotification" object:nil];
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHidden:) name:@"UIKeyboardWillHideNotification" object:nil];
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark event response
- (void)keyboardWillShow:(NSNotification *)note
{
    CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //spase大于0,则说明键盘没有遮挡scrollView不需要移动
    spase = keyboardFrame.origin.y - (textRect.origin.y + CGRectGetHeight(textFrame) + 40);
    if (spase > 0) {
        return;
    }
    //scrollView滚动到对应位置
    [self.scrollView setContentOffset:CGPointMake(0, textRectToScrollew.origin.y + keyboardFrame.size.height - CGRectGetHeight(textFrame)) animated:YES];
}

- (void)keyboardWillHidden:(NSNotification *)note
{
    if (spase > 0) {
        return;
    }
    [self.scrollView setContentOffset:CGPointMake(0, textRectToScrollew.origin.y - CGRectGetHeight(textFrame)) animated:YES];
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    //textView的父视图需要时scrollView,scrollView的父视图是self.view。如果不是使用对应的superView这个属性去获取
    //获取当前点击textView相对于self.view的位置。为了判断textView是否会被键盘遮挡,scrollView是否需要移动
    textRect = [textView convertRect:textView.bounds toView:self.view];
    //获取当前textView的fram
    textFrame = textView.frame;
    //获得当前textView相对于scrollView的位置
    textRectToScrollew = [textView convertRect:textView.bounds toView:self.scrollView];
    return YES;
}

最好不要使用;self.transform = CGAffineTransformMakeTranslation(0, spase);
这个方法,在scrollView上

相关文章

网友评论

      本文标题:scrollView中textView键盘遮挡问题处理

      本文链接:https://www.haomeiwen.com/subject/gjlxbttx.html