我有一个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确实会改变我想要的方式。
到目前为止,我尝试过的事情都没有运气:
将that.
collectionView.
contentInset设置为layoutIfNeeded()和updateConstraints() ( keyboardHeight的本地副本为let heightCopy = CGFloat(keyboardHeight) ),并将嵌入设置为。
F 222
当我将嵌入式设置为一个变量时,我真的无法理解为什么行为会有所不同,而不是仅仅将它们硬编码为同一个值。是否有人熟悉这种行为,可以帮助解决这一问题?
UPDATE:为了解决这个问题,我打算设置一些逻辑来确定要将内嵌设置到哪个硬编码值。问题是,如果我将调用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末尾的调用,它现在就可以工作了。我仍然不清楚为什么这会受到以下因素的影响:您是否将内嵌设置为硬编码常量,或者是否以某种条件包装调用是重要的,但这为我解决了问题,以防其他人遇到这种情况!
发布于 2021-01-30 11:01:55
你可以尝试的一件事就是替换
UIResponder.keyboardDidShowNotification 使用
UIResponder.keyboardWillChangeFrameNotification因为keyboardWillChangeFrameNotification会给你正确的键盘框架。
另外要注意的是,您应该用safeArea底部减去键盘的高度:
let bottomInset = keyboardHeight - view.safeAreaInsets.bottomhttps://stackoverflow.com/questions/65804205
复制相似问题