效果展示
demo.gif使用方式
(考虑到并不是每个页面中都需要加入自适应输入框的,一个项目中实际上需要也较少,按需加入更合适,节省内存占用)
- (void)viewDidLoad {
[super viewDidLoad];
[KeyBoardObserver autoScrollWithTargetView:_textField scrollView:_scrolllview];
[KeyBoardObserver autoScrollWithTargetView:_textView scrollView:_scrolllview];
}
其中 _textField和_textView是需要加入键盘自适应的实例对象,_scrolllview是它们的父级视图
实现原理
实现的代码也很少,不超过50行,已实现自动释放,支持随用随取,用完释放。
+ (void)autoScrollWithTargetView:(UIView*)targetView scrollView:(UIScrollView*)scrollView{
KeyBoardObserver *sinton = [KeyBoardObserver new];
sinton.targetView = targetView;
sinton.sv = scrollView;
objc_setAssociatedObject(targetView, associatedKey, sinton, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[[NSNotificationCenter defaultCenter] addObserver:sinton selector:@selector(keyBordDidShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:sinton selector:@selector(keyBordDidHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyBordDidHide:(NSNotification*)noti{
_responseScrollView = nil;
if (_sv && _targetView && self.isCurrentKeyboardTarget) {
[UIView animateWithDuration:0.3 animations:^{
self->_sv.contentOffset = CGPointMake(0, _tableViewOriYOffset);
}completion:^(BOOL finished) {
self.isCurrentKeyboardTarget = NO;
}];
}
}
- (void)keyBordDidShow:(NSNotification*)noti{
if (_responseScrollView != self.sv) {
_tableViewOriYOffset = _sv.contentOffset.y;
_responseScrollView = self.sv;
}
if (_sv && _targetView && [_targetView isFirstResponder]) {
self.isCurrentKeyboardTarget = YES;
CGRect keyBoardBounds = [[[noti userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
UIWindow* window = [UIApplication sharedApplication].keyWindow;
CGRect windowFrame = [_targetView.superview convertRect:_targetView.frame toView:window];
if (keyBoardBounds.origin.y <= (windowFrame.origin.y+windowFrame.size.height)) {
CGFloat offsetY = windowFrame.origin.y + windowFrame.size.height - keyBoardBounds.origin.y;
[_sv setContentOffset:CGPointMake(0, _sv.contentOffset.y + offsetY) animated:YES];
}
}
}
- (void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
网友评论