鍵盤擡起落下,輸入框相應擡起落下

-(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;

    // rectview中轉換到當前視圖中,返回在當前視圖中的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];

}


發佈了51 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章