我有一个占位符,当键盘打开和关闭时,我正在制作动画。到目前为止,当键盘打开时,它会正常动画,但是当它关闭时它会保持原位。以下是我正在使用的代码。
func setupKeyboardObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
设置键盘通知
let isKeyboardShowing = notification.name == NSNotification.Name.UIKeyboardWillShow
let isKeybobardNotShowing = notification.name == NSNotification.Name.UIKeyboardWillHide
这是动画发生的地方
DispatchQueue.main.async {
if isKeyboardShowing {
NSLayoutConstraint(item: self.placeholder, attribute: .left, relatedBy: .equal, toItem: self.searchBarView, attribute: .left, multiplier: 1, constant: 5).isActive = true
UIView.animate(withDuration: 0.5, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: {
self.view.layoutIfNeeded()
}, completion: { (completed) in
})
}
}
DispatchQueue.main.async {
if isKeybobardNotShowing {
NSLayoutConstraint(item: self.placeholder, attribute: .centerX , relatedBy: .equal, toItem: self.searchBarView, attribute: .centerX, multiplier: 1, constant: 0).isActive = true
UIView.animate(withDuration: 0.5, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: {
self.view.layoutIfNeeded()
}, completion: { (completed) in
})
}
}
有什么建议吗?
答案 0 :(得分:0)
试试这个。添加self.view.layoutIfNeeded()再一次在你的两个dispatchqueue ...
上面self.view.layoutIfNeeded()
DispatchQueue.main.async {
....
self.view.layoutIfNeeded()
}
}