我已经能够使用keyboardWillShow方法更新scrollView的布局约束。但是,当尝试在keyboardWillHide方法中执行相同操作时,布局不会更新(导致滚动视图在键盘用于启动的位置被切断)。关于如何解决这个问题的任何提示?谢谢!
@objc func keyboardWillShow(notification: NSNotification) {
let info = notification.userInfo!
let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
keyboardHeightSubtraction = keyboardFrame.size.height
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -keyboardHeightSubtraction).isActive = true
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
@objc func keyboardWillHide(notification: NSNotification) {
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
答案 0 :(得分:2)
问题是你目前在约束中创建了冲突,所以在viewDidLoad
中创建一次,并在这两个函数中管理它的常量\
var botCon:NSLayoutConstraint!
//
botCon = scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
botcon.isActive = true
//
@objc func keyboardWillShow(notification: NSNotification) {
let info = notification.userInfo!
let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
botCon.constant = -1 * keyboardHeightSubtraction
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
@objc func keyboardWillHide(notification: NSNotification) {
botCon.constant = 0
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
答案 1 :(得分:1)
您可以使用UIEdgeInsects
并捕获键盘的高度并根据您的视图添加自定义填充以从底部空间滚动视图,并在keyBoard关闭时将scrollView Insect设置回零。
var contentPadding: CGFloat = 60
KeyBoard将出现
func keyboardWillShow(notification: NSNotification) {
var userInfo = notification.userInfo!
var keyboardFrame: CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
keyboardFrame = self.view.convert(keyboardFrame, from: nil)
var contentInset: UIEdgeInsets = self.scrollView.contentInset
contentInset.bottom = keyboardFrame.size.height + contentPadding // custom padding
scrollView.contentInset = contentInset
}
键盘会消失
func keyboardWillHide(notification: NSNotification) {
let contentInset: UIEdgeInsets = UIEdgeInsets.zero
scrollView.contentInset = contentInset
}
答案 2 :(得分:0)
另一种方式。看起来您希望在键盘出现时让您的视图向上移动,您可以使用IQKeyboardManager窗格来实现它。它使用起来非常简单,并且可以避免在每个应该具有此行为的视图中进行更改。