ios技术iOS技术ios学习

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

2015-03-29  本文已影响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];

}

上一篇下一篇

猜你喜欢

热点阅读