iOS 根据键盘的高度动态改变UIView的高度

在我们使用键盘时常常出现键盘挡着视图这种情况,下面我给大家介绍一种方法可以根据键盘的高度来动态改变视图的度使其可以始终在键盘的上边

在这里视图我用TextView

UIKeyboardWillShowNotification//键盘弹出
UIKeyboardWillHideNotification//键盘缩回
   //用通知监听键盘的弹出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboarShow:) name:UIKeyboardWillShowNotification object:nil];
   
   //监听键盘的缩回
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardHiden:) name:UIKeyboardWillHideNotification object:nil];
   
    //设置delegate
    _myTextView.delegate=self;
   

    // Do any additional setup after loading the view, typically from a nib.
}
//显示
-(void)keyboarShow:(NSNotification *)notification{
   //获取键盘的高度
    CGRect rect =[notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
   //计算出 textView的height
    CGRect textViewRect=_myTextView.frame;
     CGFloat height=textViewRect.size.height-rect.size.height;
    textViewRect.size.height=height;
    [UIView animateWithDuration:.2 animations:^{
        self.myTextView.frame=textViewRect;
    }];
}
//键盘隐藏时调用
-(void)keyBoardHiden:(NSNotification *)notification{
    _myTextView.frame=self.view.frame;
}
 
这样就可以达到我们想要的效果了  如果有什么问题可以提问哦。大家一起学习

posted on 2016-10-20 19:17  freeCrank  阅读(2038)  评论(0编辑  收藏  举报

导航