键盘弹出事件

来源:互联网 发布:重装系统 知乎 编辑:程序博客网 时间:2024/04/29 16:06

将键盘弹出事件抽离,可以控制键盘弹起时视图的控制,主要用于控制view、tableView、scrollView

- (instancetype)init {

    if (self = [superinit]) {

        [selfkeyBoard];

    }

    returnself;

}


+ (instancetype)keyBoardWithSuperView:(UIView *)superView scrollView:(UIScrollView *)scrollView delegate:(id)delegate {

    LJBKeyBoard *keyBoard = [[selfalloc] init];

    keyBoard.delegate = delegate;

    [superView addSubview:keyBoard];

    keyBoard.superView = superView;

    keyBoard.scrollView = scrollView;

    

    return keyBoard;

}


- (void)keyBoard {

    //键盘弹出的通知。

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyBoardShow:)name:UIKeyboardWillShowNotificationobject:nil];

    //键盘隐藏的通知。

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyBoardHide:)name:UIKeyboardWillHideNotificationobject:nil];

}


#pragma mark - 获取键盘弹出通知

- (void)keyBoardShow:(NSNotification *)note {

    NSDictionary *dict = note.userInfo;

    CGRect endRect = [dict[@"UIKeyboardFrameEndUserInfoKey"]CGRectValue];

    CGFloat endKeyY =0;

    UIView *view =self.superView;

    if ([[[UIDevicecurrentDevice] 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.delegateljbKeyBoardGetMaxY];

    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

[LJBKeyBoardkeyBoardWithSuperView:self.viewscrollView:nildelegate:self];

2.实现代理返回具体的位置

#pragma mark - 键盘代理事件(必须实现以下代理)

- (CGFloat)ljbKeyBoardGetMaxY {

    UITextField *textField = (UITextField *)[self.viewviewWithTag:self.selTag];

    returnCGRectGetMaxY(textField.frame);

}



0 0
原创粉丝点击