iOS 键盘遮挡输入框解决方案

本文介绍了两种处理iOS应用中键盘弹出与隐藏时视图调整的方法。第一种使用NSNotification来监听键盘显示与隐藏的通知,调整视图的高度。第二种通过UITextField代理方法,在开始编辑时调整视图位置,并在结束编辑时恢复原始状态。

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

// 方法一

- (void)addNotification {

[[NSNotificationCenter defaultCenteraddObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

[[NSNotificationCenter defaultCenteraddObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

}


- (void)keyboardWillShow:(NSNotification *)info {

    CGRect keyboardBounds = [[[infouserInfo] objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];

    float f =  keyboardBounds.size.height;

    self.view.frame =CGRectMake(0,0,f, 0);

    

}


- (void)keyboardWillHide:(NSNotification *)info {

    self.view.frame =CGRectMake(self.view.frame.size.height,0, 0,0);

}

// 方法二

// 开始编辑输入弹出键盘

- (void)textFieldDidBeginEditing:(UITextField *)textField {

    CGRect frame = textField.frame;

    int offset = frame.origin.y + 32 - (self.view.frame.size.height - 216.0);//键盘高度216

    

    NSTimeInterval animationDuration = 0.30f;

    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];

    [UIView setAnimationDuration:animationDuration];

    

    //将视图的Y坐标向上移动offset个单位,以使下面腾出地方用于软键盘的显示

    if(offset > 0)

        self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);

    

    [UIView commitAnimations];

}


// 当用户按下return键收回键盘

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    [textField resignFirstResponder];

    return YES;

}


// 输入框编辑完成后,将视图恢复到原始状态

- (void)textFieldDidEndEditing:(UITextField *)textField {

    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值