我試圖在出現鍵盤時爲包含登錄表單的我的UIStackView
設置動畫。我只想通過調整故事板文件的約束來實現。使用鍵盤動畫調整約束約束
這是我的佈局:
我的代碼重新調整底部約束,取決於鍵盤的大小。
@IBOutlet var keyboardHeightLayoutConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardNotification(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
keyboardHeightLayoutConstraint.isActive = false
}
func keyboardNotification(notification: NSNotification) {
keyboardHeightLayoutConstraint.isActive = true
if let userInfo = notification.userInfo {
let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
let duration:TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions.curveEaseInOut.rawValue
let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)
if (endFrame?.origin.y)! >= UIScreen.main.bounds.size.height {
self.keyboardHeightLayoutConstraint?.constant = 0.0
} else {
self.keyboardHeightLayoutConstraint?.constant = (endFrame?.size.height)! + 20
}
UIView.animate(withDuration: duration,
delay: TimeInterval(0),
options: animationCurve,
animations: { self.view.layoutIfNeeded() },
completion: nil)
}
}
的結果是,它只是縮小了UIStackView的大小,因爲頂部約束不會允許它向上移動,例如:
這與頂部約束做我的堆棧視圖。刪除此約束可解決問題,但在較小的分辨率下,表單可能與UIImageView
重疊。有沒有辦法更新這個約束來反映底部約束的變化?
這正是我想要的。這是否意味着我需要底部出口限制和頂部出口限制?可以說,如果底部得到+20頂部應該得到-20?這將工作,沒有得到約束衝突? – Hapeki
是的,這正是我所做的。 –
然後當你隱藏鍵盤時,你會改變這個變化(從底部減去20,並將頂部加20) –