-(void)myViewLayout
{
// 旋轉不能用frame 要用bounds,
self.inputView.frame = CGRectMake(0, self.view.bounds.size.height- self.bottomLayoutGuide.length-45, self.view.bounds.size.width, 45);
}
-(void)viewDidLayoutSubviews
{
[self myViewLayout];
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(keyboardAppear:) name:UIKeyboardWillShowNotification object:nil];
[center addObserver:self selector:@selector(keyboardDisappear:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyboardAppear:(NSNotification *)notification
{
//1. 獲取鍵盤的高度
NSDictionary *userinfo = notification.userInfo;
NSValue *value = [userinfo valueForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardFrame = [value CGRectValue];
UIWindow *window = [[UIApplication sharedApplication] delegate].window;
// 將rect從view中轉換到當前視圖中,返回在當前視圖中的rect
keyboardFrame = [self.view convertRect:keyboardFrame fromView:window];
//2. 計算輸入框的frame
CGRect frame = self.inputView.frame;
frame.origin.y = self.view.bounds.size.height - keyboardFrame.size.height - frame.size.height;
//3. 動畫
//NSTimeInterval duration = [userinfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] + 0.1;
// 鍵盤的動畫時間+0.1
NSTimeInterval duration = [[userinfo valueForKey: UIKeyboardAnimationDurationUserInfoKey] doubleValue] + 0.1;
UIViewAnimationOptions options = [userinfo[UIKeyboardAnimationCurveUserInfoKey]unsignedIntegerValue];
[UIView animateWithDuration:duration
delay:0
options:options
animations:^{
self.inputView.frame = frame;
} completion:nil];
}
- (void)keyboardDisappear:(NSNotification *)notification
{
CGRect frame = self.inputView.frame;
frame.origin.y = self.view.bounds.size.height - frame.size.height - self.bottomLayoutGuide.length;
self.inputView.frame = frame;
}
- (IBAction)didInput:(UITextField *)sender
{
[sender resignFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}