iOS 根据键盘的高度动态改变UIView的高度
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}];
[[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;
}
_myTextView.frame=self.view.frame;
}
这样就可以达到我们想要的效果了 如果有什么问题可以提问哦。大家一起学习
以上是关于iOS 根据键盘的高度动态改变UIView的高度的主要内容,如果未能解决你的问题,请参考以下文章
iOS Swift - 动态增加 UITextView 和父 UIView 的高度