view初始化時增長通知:windows
{code}ide
//增長監聽,當鍵盤出現或改變時收出消息spa
[[NSNotificationCenter defaultCenter] addObserver:selfcode
selector:@selector(keyboardWillShow:)server
name:UIKeyboardWillShowNotificationio
object:nil];class
//增長監聽,當鍵退出時收出消息object
[[NSNotificationCenter defaultCenter] addObserver:selfselect
selector:@selector(keyboardWillHide:)scroll
name:UIKeyboardWillHideNotification
object:nil];
{code}
鍵盤彈起和收起時觸發的動做
{code}
- (void)keyboardWillShow:(NSNotification *)notification {
if (!_highlightedTextField) {// 當前焦點TextField
return;
}
UIView *view = [self superview];
while (![view isKindOfClass:[UIScrollView class]] &&
[view superview]) {
view = [view superview];
}
if (![view isKindOfClass:[UIScrollView class]]) {
return;
}
UIScrollView *scrollView = (UIScrollView *)view;
CGSize kbSize = [[notification.userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
CGFloat keyboardHeight = kbSize.height;
UITextField *textField = _highlightedTextField;
if ([UIApplication sharedApplication].windows.count == 0) {
return;
}
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardHeight, 0.0);
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
UIWindow *window = [UIApplication sharedApplication].windows[0];
CGRect textRect = [scrollView convertRect:textField.bounds fromView:textField];
CGRect scrollRect = [window convertRect:scrollView.bounds fromView:scrollView];
CGFloat scrollBottomMargin = window.height - scrollRect.origin.y - scrollRect.size.height;
CGFloat offset = textRect.origin.y + textRect.size.height - scrollView.contentOffset.y - scrollBottomMargin - (scrollView.height - keyboardHeight);
if (offset > 0) {
CGPoint scrollPoint = CGPointMake(0.0, scrollView.contentOffset.y + offset);
[scrollView setContentOffset:scrollPoint animated:YES];
}
}
- (void)keyboardWillHide:(NSNotification *)notification{
UIView *view = [self superview];
while (![view isKindOfClass:[UIScrollView class]] &&
[view superview]) {
view = [view superview];
}
if (![view isKindOfClass:[UIScrollView class]]) {
return;
}
UIScrollView *scrollView = (UIScrollView *)view;
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
}
{code}