iOS中在tableview上通知控制键盘弹起界面上推的方法

本文介绍如何使用iOS的通知中心来监听键盘的显示和隐藏事件,并调整布局以适配键盘的弹出与收起。此外,还实现了当tableView滚动时自动收起键盘的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上代码:

//注册通知

-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];

     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(openKeyboard:) name:UIKeyboardWillShowNotification object:nil];

     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(closeKeyboard:) name:UIKeyboardWillHideNotification object:nil];

}

//注销通知

-(void)viewDidDisAppear:(BOOL)animated{

     [super viewDidDisappear:animated];

     [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];


     [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];

}

//键盘上弹

-(void)openKeyboard:(NSNotification *)notification{

     CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];

     NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey]doubleValue];

     UIViewAnimationOptions option = [notification.userInfo [UIKeyboardAnimationCurveUserInfoKey]intValue];

    //  self.BottomLayoutConstaint.constant 这个是storyboard里面tableview的下沿,直接拉线的,而keyboardFrame.size.height是键盘的高度

     self.BottomLayoutConstaint.constant = keyboardFrame.size.height+99*SizeScaleY;

     [UIView animateWithDuration:duration delay:0 options:option animations:^{

          [self.view layoutIfNeeded];

     } completion:nil];

}

//恢复键盘

-(void)closeKeyboard:(NSNotification *)notification{

    

     self.BottomLayoutConstaint.constant = 0;

     NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey]doubleValue];

     UIViewAnimationOptions option = [notification.userInfo [UIKeyboardAnimationCurveUserInfoKey]intValue];

     [UIView animateWithDuration:duration delay:0 options:option animations:^{

          [self.view layoutIfNeeded];

     } completion:nil];


}

//tableView滚动的时候自动收回键盘

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView

{

    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];


}

如上面设置就可以实现键盘的上弹和收回了,当然要灵活运用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值