iOS键盘弹出完美移动控件

本文介绍如何在iOS应用中监听键盘的Frame变化,以便在键盘弹出时实现控件的自动移动,确保用户体验。在ViewWillAppear中添加监听,并在视图消失时移除。

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

添加监听(最好放在ViewWillAppear里, 在视图将要消失时移除监听)

这里监听键盘Frame的变化而不是监听键盘的显示和隐藏

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];

实现方法

_toolBar是要移动的View控件
#pragma mark - 键盘Frame改变时调用
-(void)keyboardFrameChange:(NSNotification *)note
{
    CGFloat durtion = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];

    CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];

    if (frame.origin.y == self.view.frame.size.height)
    {
        // 没有弹出键盘
        [UIView animateWithDuration:durtion animations:^{

            _toolBar.transform = CGAffineTransformIdentity;
        }];
    }
    else
    {
        // 弹出键盘
        // 工具条向上移动键盘的高度
        [UIView animateWithDuration:durtion animations:^{

            _toolBar.transform = CGAffineTransformMakeTranslation(0, -frame.size.height);
        }];
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值