键盘遮挡控件(textfield/textview.......)

采用的是通知的常规方式

    // 解决键盘遮挡问题
//选择didShow是因为需要键盘的高度
//选择willHide是因为视图frame重置需要优先于键盘消失,否则表现得不连贯
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHide:) name:UIKeyboardWillHideNotification object:nil];

触发的方法

-(void)keyboardWasShown:(NSNotification*)notification
{
    //获取键盘高度
    NSValue* value=notification.userInfo[UIKeyboardFrameBeginUserInfoKey];
    CGFloat keyBoradHeight=[value CGRectValue].size.height;
    NSNumber* animationTime=notification.userInfo[UIKeyboardAnimationDurationUserInfoKey];
    double time=[animationTime doubleValue];
    //获取被遮挡控件距离controller底部的距离
    float a=self.view4.frame.origin.y+self.view4.frame.size.height;
    float b = self.view.frame.size.height-a;
    if (b<keyBoradHeight)
    {
        //动画效果
        [UIView animateWithDuration:time
                         animations:^
         {
             //键盘被挡住了
             CGRect viewCGrect=self.view.frame;
             //视图应该上移所以是-
             viewCGrect.origin.y=viewCGrect.origin.y-(keyBoradHeight-b);
             [self.view setFrame:viewCGrect];

         } completion:nil];


    }

}
-(void)keyboardWasHide:(NSNotification*)notification
{
    NSValue* value=notification.userInfo[UIKeyboardFrameBeginUserInfoKey];
    CGFloat keyBoradHeight=[value CGRectValue].size.height;

    float a=self.view4.frame.origin.y+self.view4.frame.size.height;
    float b = self.view.frame.size.height-a;
    
         CGRect viewCGrect=self.view.frame;
         viewCGrect.origin.y=viewCGrect.origin.y+(keyBoradHeight-b);
         [self.view setFrame:viewCGrect];



}

最后移除通知

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardDidShowNotification
                                                  object:nil];

}

 最终测试改方式只适用于输入控件比较少的界面,更多的可以使用gitHub上第三方

DaidoujiChen / DaiDodgeKeyboard

hackiftekhar / IQKeyboardManager


键盘遮挡输入框的问题 - 小小流浪 - 博客园

 

转载于:https://www.cnblogs.com/louyizhidu/p/4953221.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值