1.在- (void)viewDidLoad 中
//注册通知监听器,监听键盘弹起事件
[[NSNotificationCenter defaultCenter]addObserver:selfselector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotificationobject:nil];
//注册通知监听器,监听键盘收起事件
[[NSNotificationCenter defaultCenter]addObserver:selfselector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotificationobject:nil];
2.
//屏幕有限,键盘弹起会遮挡填写数据的界面。程序界面上移,改变Y坐标,实现弹起和落下的效果。。。在ViewDidLoad方法中添加键盘弹起和关闭事件的监听
//键盘弹出时激发该方法
-(void)keyboardWillShow:(NSNotification*)notification
{
//开始视图升起动画效果
[UIView beginAnimations:@"keyboardWillShow" context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
//获取主视图View的位置
CGRect rect=self.view.frame;
rect.origin.y = -60;
//更改主视图View的位置
self.view.frame = rect;
//结束动画
[UIView commitAnimations];
}
//键盘关闭时激发该方法
-(void)keyboardWillHide:(NSNotification*)notification
{
//开始视图下降动画效果
[UIView beginAnimations:@"keyboardWillHide" context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
//获取主视图View的位置
CGRect rect = self.view.frame;
rect.origin.y = 0;
//恢复主视图View的位置
self.view.frame = rect;
//结束动画
[UIView commitAnimations];
}
-(void)dealloc
{
//移除通知监听器
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
本文介绍了如何在iOS应用中处理键盘弹起时界面被遮挡的问题。通过在`viewDidLoad`中注册键盘事件监听器,并实现`keyboardWillShow:`和`keyboardWillHide:`方法,进行视图的上移和下移动画,确保用户能正常填写数据。在`dealloc`方法中移除监听器以释放资源。

3283

被折叠的 条评论
为什么被折叠?



