iOS textField鍵盤彈出/收起 自動上下移

weixin_34208283發表於2018-07-12

程式碼如下:

  • (void)viewDidLoad {

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

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

}

pragma mark - 鍵盤即將跳出

-(void)didClickKeyboard:(NSNotification *)sender{

CGFloat durition = [sender.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];

CGRect keyboardRect = [sender.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];

CGFloat keyboardHeight = keyboardRect.size.height;

[UIView animateWithDuration:durition animations:^{

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

}];

}

pragma mark - 當鍵盤即將消失

-(void)didKboardDisappear:(NSNotification *)sender{

CGFloat duration = [sender.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];

[UIView animateWithDuration:duration animations:^{

self.view.transform = CGAffineTransformIdentity;

}];

}

作者:gainna
連結:https://www.jianshu.com/p/414c2533caa7
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯絡作者獲得授權並註明出處。

相關文章