您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS Dev (54):鍵盤彈出與收起時讓 view 隨之移動

編輯:iOS 開發綜合

當鍵盤彈出會遮住輸入框時,需要讓 view 跟著鍵盤上移,收起時再復位。做法是監聽鍵盤的通知。

添加監聽:

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

移除監聽:

[[NSNotificationCenter defaultCenter] removeObserver:self
                                                name:UIKeyboardWillShowNotification
                                              object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
                                                name:UIKeyboardWillHideNotification
                                              object:nil];

事件處理函式:從通知中取出鍵盤最終位置與動畫參數,讓 view 平滑移動到鍵盤上方。

- (void)changeContentViewPosition:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGFloat keyBoardEndY = value.CGRectValue.origin.y;

    NSNumber *duration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];

    [UIView animateWithDuration:duration.doubleValue animations:^{
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationCurve:[curve intValue]];
        self.view.center = CGPointMake(self.view.center.x,
                                       keyBoardEndY - STATUS_BAR_HEIGHT - self.view.bounds.size.height / 2.0);
    }];
}

透過沿用鍵盤自身的動畫曲線與時長,view 的位移就能與鍵盤的彈出/收起保持同步,視覺上更自然。

參考資料

  • https://www.cnblogs.com/programmer-blog/p/3265110.html
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved