在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上
网友评论