1,在页面中添加一些控件,必须要有UITextFiled,如图
// 在viewWillAppear方法中添加两个通知,显示键盘和收起键盘
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
//添加键盘 TextField 监听
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
// 隐藏键盘监听
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
// 显示键盘
- (void)keyboardWillShow :(NSNotification *)note
{
//completeBtn为图中的"完成"按钮,当开始输入时完成按钮离键盘的高度为20以上
CGFloat height= MAINHEIGHT-_completeBtn.frame.origin.y-_completeBtn.frame.size.height;
CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//保证键盘跟确认按钮之间间隔为20以上,当间隔小于20的时候向上偏移
if (height-rect.size.height<20) {
CGFloat ty=height-rect.size.height-20;
[UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{
self.view.transform = CGAffineTransformMakeTranslation(0, ty);
}];
}
}
// 收键盘
- (void)keyboardWillHide :(NSNotification *)note
{
[UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{
self.view.transform = CGAffineTransformMakeTranslation(0, 0);
}];
}
本文介绍了一个iOS应用中处理键盘弹出和隐藏时视图自动调整的方法。通过在viewWillAppear方法中添加键盘显示和隐藏的通知,确保了键盘出现时UI元素的位置调整,并在键盘消失时恢复原位。
1342

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



