ios-利用键盘通知处理键盘出现时遮挡控件问题

本文介绍了一个iOS应用如何通过NSNotificationCenter来监听键盘的显示和隐藏事件,并根据键盘高度的变化调整视图的位置,防止输入框被键盘遮挡的问题。

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

-(void)viewDidLoad {
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    
    //注册键盘显示通知
    [center addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    //注册键盘隐藏通知
    [center addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

-(void)viewDidDisappear:(BOOL)animated
{

    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];

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

- (void) keyboardWillShow:(NSNotification *) notification{
    
    NSDictionary *info;
    CGSize kbSize;
    double kbheight;
    CGFloat Oversize;
    double duraction;
    
    info = notification.userInfo;
    kbSize = [[info objectForKey: UIKeyboardFrameEndUserInfoKey]
CGRectValue].size;
    kbheight = kbSize.height;
    
    Oversize = (self.view.frame.size.height - kbheight) - (textfield.frame.origin.y + textfield.frame.size.height+5);
    
    duraction =  [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    if (Oversize < 0){
        [UIView animateWithDuration: duraction animations:^{
            self.view.frame = CGRectMake(0.0f, Oversize, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
}

-(void) keyboardWillHide:(NSNotification *) notification{
    
    double duraction = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duraction animations:^{
        self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }];
}

 

转载于:https://www.cnblogs.com/cccliche/p/9123854.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值