- (void)setNotification {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
- (void)closeNotification
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}
- (void)keyboardWillChangeFrame:(NSNotification *)notification {
NSDictionary *dict = [notification userInfo];
// 键盘弹出和收回的时间
CGFloat duration = [[dict objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
// 键盘初始时刻的frame
CGRect beginKeyboardRect = [[dict objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
// 键盘停止后的frame
CGRect endKeyboardRect = [[dict objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
// 相减为键盘高度
CGFloat yOffset = endKeyboardRect.origin.y - beginKeyboardRect.origin.y;
// 创建appDelegate单例对象
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
// 初始化一个数组,UIWindow的所有子视图
NSArray *array = appDelegate.window.subviews;
// 获取当前Controller的view视图
UIView *view = appDelegate.window.subviews[array.count - 1];
// textField相对于UIWindow的frame
CGRect selfFrameFromUIWindow = [self convertRect:self.bounds toView:appDelegate.window];
// textField底部距离屏幕底部的距离
CGFloat bottomHeight = [UIScreen mainScreen].bounds.size.height - selfFrameFromUIWindow.origin.y - selfFrameFromUIWindow.size.height;
// 初始化一个frame,大小为UIWindow的frame
CGRect windowFrame = appDelegate.window.frame;
// 把这个frame的y值增加或减少相应的高度(这里的40是textField底部和键盘顶部的距离)
windowFrame.origin.y += yOffset + bottomHeight - 40;
// 根据yOffset判断键盘是弹出还是收回
if (yOffset < 0) {
// 键盘弹出,改变当前Controller的view的frame
[UIView animateWithDuration:duration animations:^{
view.frame = windowFrame;
}];
} else {
// 键盘收回,把view的frame恢复原状
[UIView animateWithDuration:duration animations:^{
view.frame = appDelegate.window.frame;
}];
}
}iOS开发TextField根据键盘自适应位置
最新推荐文章于 2017-10-31 10:21:54 发布
本文介绍了一个iOS应用如何通过监听键盘的通知来调整视图的位置,确保文本框不会被键盘遮挡。文章详细解释了如何设置和移除键盘变化的通知观察者,并提供了具体的实现代码。
321

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



