平时收藏iOS学习笔记iOS学习开发

OC中键盘的处理

2016-09-17  本文已影响229人  打电话记错号码的人

作品链接:
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 - <UITableViewDelegate>
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    // 退出键盘
    [self.view endEditing:YES];
}

上一篇下一篇

猜你喜欢

热点阅读