将键盘弹出事件抽离,可以控制键盘弹起时视图的控制,主要用于控制view、tableView、scrollView
- (instancetype)init {
if (self = [super init]) {
[self keyBoard];
}
return self;
}
+ (instancetype)keyBoardWithSuperView:(UIView *)superView scrollView:(UIScrollView *)scrollView delegate:(id)delegate {
LJBKeyBoard *keyBoard = [[self alloc] init];
keyBoard.delegate = delegate;
[superView addSubview:keyBoard];
keyBoard.superView = superView;
keyBoard.scrollView = scrollView;
return keyBoard;
}
- (void)keyBoard {
//键盘弹出的通知。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillShowNotification object:nil];
//键盘隐藏的通知。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardHide:) name:UIKeyboardWillHideNotification object:nil];
}
#pragma mark - 获取键盘弹出通知
- (void)keyBoardShow:(NSNotification *)note {
NSDictionary *dict = note.userInfo;
CGRect endRect = [dict[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
CGFloat endKeyY = 0;
UIView *view = self.superView;
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
endKeyY = view.frame.size.height - endRect.size.width;
} else {
endKeyY = endRect.origin.y;
}
UIScrollView *scrollView = self.scrollView;
CGPoint offSet = scrollView.contentOffset;
CGFloat currTextMaxY = [self.delegate ljbKeyBoardGetMaxY];
CGFloat Fheight = (scrollView.frame.origin.y + currTextMaxY-offSet.y);
if (Fheight > endKeyY) {
view.transform = CGAffineTransformMakeTranslation(0, endKeyY - Fheight);
}
}
#pragma mark - 获取键盘隐藏通知
- (void)keyBoardHide:(NSNotification *)note {
self.superView.transform = CGAffineTransformIdentity;
}
1.具体的使用步骤 viewDidLoad 中定义事件 如果为tableview或者scrollview上弹起时,scrollview:传递具体的参数scrollView:self.tableView、scrollView:self.scrollView
[LJBKeyBoard keyBoardWithSuperView:self.view scrollView:nil delegate:self];
2.实现代理返回具体的位置
#pragma mark - 键盘代理事件(必须实现以下代理)
- (CGFloat)ljbKeyBoardGetMaxY {
UITextField *textField = (UITextField *)[self.view viewWithTag:self.selTag];
return CGRectGetMaxY(textField.frame);
}