如何解决UIEdgeInsets 具有变量和硬编码值的不同行为
我有一个 UICollectionView
约束在 UIViewController
的边缘。我想在显示键盘时更新 UICollectionView
的底部插图,以免隐藏 UICollectionView
底部的项目。为此,我设置了一个观察者如下:
override func viewDidLoad() {
super.viewDidLoad()
...
NotificationCenter.default.addObserver(self,selector: #selector(keyboard(onScreen:)),name: UIResponder.keyboardDidShowNotification,object: nil)
}
@objc func keyboard(onScreen notification: Notification?) {
let info = notification?.userInfo
let value = info?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue
guard let keyboardHeight = value?.cgRectValue.size.height else { return }
print("Keyboard height: \(keyboardHeight)") // This prints out 371.0
// This does not change anything in the UI
collectionView.contentInset.bottom = keyboardHeight
collectionView.verticalScrollIndicatorInsets.bottom = keyboardHeight
// This updates the UI correctly
collectionView.contentInset.bottom = 371.0
collectionView.verticalScrollIndicatorInsets.bottom = 371.0
}
只要出现键盘,就会正确调用 keyboard
函数,并打印出正确的高度,如上面代码中的注释所示。
问题是,如果我将 contentInset
设置为从键盘 Notification
获得的变量,UI 不会发生任何变化。如果我硬编码完全相同的值 (371.0),UI 确实会改变我想要的方式。
到目前为止我尝试过但没有运气的事情:
- 将
keyboardHeight
的值存储在类变量中并将contentInset
设置为该值。 - 在
layoutIfNeeded()
上调用updateConstraints()
和collectionView
。 - 创建
keyboardHeight
的本地副本为let heightCopy = CGFloat(keyboardHeight)
,并将插入设置为该副本。
我真的无法理解为什么当我将 insets 设置为变量时,与我将它们硬编码为相同值时的行为会有所不同。有没有熟悉这种行为的人可以帮助解决这个问题?
更新:为了解决这个问题,我打算设置一些逻辑来决定将插入设置为哪个硬编码值。问题是,如果我将调用 collectionView.contentInset.bottom = 371.0
包装在 if 语句中,它不再起作用,即使它确实执行了。澄清:
collectionView.contentInset.bottom = 371.0 // This updates the UI correctly
鉴于:
if (some statement that is true) {
print("if passed")
collectionView.contentInset.bottom = 371.0
print("insets set")
}
不会导致对 UI 的任何更改,即使打印语句出现在输出中。我觉得我在这里要疯了。任何和所有想法都将不胜感激!
更新 2: 如果我在设置插入后添加滚动到 UICollectionView
末尾的调用,它现在可以工作了。我仍然不清楚为什么这会受到您是否将插入设置为硬编码常量的影响,或者为什么您是否以某种条件包装调用很重要,但这对我来说解决了问题,以防其他人遇到这个!
解决方法
你可以尝试的一件事是替换
UIResponder.keyboardDidShowNotification
与
UIResponder.keyboardWillChangeFrameNotification
因为 keyboardWillChangeFrameNotification
将始终为您提供正确的键盘框架。
还有一点要注意,你应该用safeArea底部减去键盘高度:
let bottomInset = keyboardHeight - view.safeAreaInsets.bottom
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。