簡體   English   中英

出現鍵盤時移動垂直居中的內容

[英]Moving Vertically Centered Content when Keyboard appears

我有一個垂直居中的注冊表格。

當鍵盤出現時,我想為其上移動畫。

但是我的實現:

1-移除Align center Y to: Superview

2-鈎入鍵盤框架

3-基於鍵盤框架安裝約束

進行非常靜態的位移,沒有動畫。

@IBOutlet weak var centerVertically: NSLayoutConstraint!
@IBOutlet weak var bottomDistance: NSLayoutConstraint!

(...)

func keyboardWillShow(notification: NSNotification) {
    var info = notification.userInfo!
    let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
    bottomDistance.constant = keyboardFrame.size.height + 20

    UIView.animateWithDuration(2.0) { () -> Void in
        self.view.removeConstraint(self.centerVertically)
        self.view.addConstraint(self.bottomDistance)
    }
}

func keyboardWillHide(notification: NSNotification) {
    UIView.animateWithDuration(2.0) { () -> Void in
        self.view.removeConstraint(self.bottomDistance)
        self.view.addConstraint(self.centerVertically)
    }
}

如何正確設置過渡動畫?

結合幾件事,首先您可以加入鍵盤移動的動畫周期,以便動畫可以同時/持續進行動畫處理。

其次,不要添加和刪除約束(這將導致視圖在不進行動畫處理的情況下就位),而是更新動畫塊內約束的常量值。 這是我在Objective-C中使用的代碼片段,快速版本應該很簡單。

[[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillHideNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        UIViewAnimationCurve curve = [[note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
        double duration = [[note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        [UIView animateWithDuration:duration
                              delay:0
                         options:UIViewAnimationOptionBeginFromCurrentState
                         animations:^{
                             [UIView setAnimationCurve:curve];
                             this.verticalConstraint.constant = 100.0f;
                             [this.view layoutIfNeeded];
                         }
                         completion:nil];
        [UIView commitAnimations];

    }];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM