在viewDidLoad里面創(chuàng)建兩個監(jiān)聽鍵盤出來和隱藏的通知
[[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滾動到對應(yīng)位置
[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缭受。如果不是使用對應(yīng)的superView這個屬性去獲取
//獲取當(dāng)前點(diǎn)擊textView相對于self.view的位置牢屋。為了判斷textView是否會被鍵盤遮擋弄捕,scrollView是否需要移動
textRect = [textView convertRect:textView.bounds toView:self.view];
//獲取當(dāng)前textView的fram
textFrame = textView.frame;
//獲得當(dāng)前textView相對于scrollView的位置
textRectToScrollew = [textView convertRect:textView.bounds toView:self.scrollView];
return YES;
}
最好不要使用;self.transform = CGAffineTransformMakeTranslation(0, spase);
這個方法狸膏,在scrollView上