OC中键盘的处理

作品链接:
http://www.jianshu.com/users/1e0f5e6f73f6/top_articles

  • 使用通知的方法

1.监听键盘通知

- (void)viewDidLoad {
    [super viewDidLoad]; 
    // 监听键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

2.取消通知

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

3.键盘处理

#pragma mark - 键盘处理
- (void)keyboardWillChangeFrame:(NSNotification *)note {
    // 取出键盘最终的frame
    CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    // 取出键盘弹出需要花费的时间
    double duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    // 修改transform
    [UIView animateWithDuration:duration animations:^{
        // 平移多少  rect.origin.y  键盘高度
        CGFloat ty = [UIScreen mainScreen].bounds.size.height - rect.origin.y;
        self.view.transform = CGAffineTransformMakeTranslation(0, - ty);
    }];
}

4.退出键盘

#pragma mark - 
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    // 退出键盘
    [self.view endEditing:YES];
}

你可能感兴趣的:(OC中键盘的处理)