首页 > 代码库 > iOS 根据键盘的高度动态改变UIView的高度
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的高度
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。