美文网首页ios技术iOS技术ios学习
设置视图随着键盘的弹出收起来上移还原

设置视图随着键盘的弹出收起来上移还原

作者: _李布斯 | 来源:发表于2015-03-29 13:19 被阅读1568次

首先是效果图:

gif

实现原理:

// 注册键盘的通知

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

- (void)keyboardWillChangeFrame:(NSNotification*)note{

//设置窗口的颜色

self.view.window.backgroundColor = self.view.backgroundColor;

// 取出键盘动画的时间

CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

// 取得键盘最后的frame

CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];

// 计算控制器的view需要平移的距离

CGFloat transformY = keyboardFrame.origin.y - self.view.frame.size.height;

// 执行动画

[UIView animateWithDuration:duration animations:^{

self.view.transform = CGAffineTransformMakeTranslation(0, transformY);

}];

}

// 点击view收起键盘

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event

{

[self.view endEditing:YES];

}

// 最后别忘了在销毁控制器的时候删除通知

- (void)dealloc

{

[[NSNotificationCenter defaultCenter] removeObserver:self];

}

相关文章

网友评论

  • Cb724r:很长的 需要滚动的视图就不能解决了。。。

本文标题:设置视图随着键盘的弹出收起来上移还原

本文链接:https://www.haomeiwen.com/subject/dwinxttx.html