iOS输入框上移

2016-01-30  本文已影响609人  白牛桑

有时候UI设计的输入框太低,我们点击输入框弹出键盘可能会挡住输入框,所以要让视图上移;

代码如下:

#pragma mark - 键盘高度

-(void)viewWillAppear:(BOOL)animated

{

[super viewWillAppear:animated];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];

}

/*!

*  @brief  显示键盘及设置高度

*

*  @param note 通知消息-需要设置的高度

*/

-(void)keyboardShow:(NSNotification *)note

{

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

CGFloat deltaY=keyBoardRect.size.height;

[UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{

self.view.transform=CGAffineTransformMakeTranslation(0, -deltaY);

}];

}

/*!

*  @brief  隐藏键盘及设置高度

*

*  @param note 通知消息-需要设置的高度

*/

-(void)keyboardHide:(NSNotification *)note

{

[UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{

self.view.transform = CGAffineTransformIdentity;

}];

}

这段代码表示点击输入框,整个self.view会根据键盘高度上移,然后随着键盘消失,self.view回到原来位置(直接复制粘贴代码即可)

上一篇下一篇

猜你喜欢

热点阅读