【发布时间】:2019-08-02 03:06:38
【问题描述】:
这不是关于当键盘上升和下降时提升collectionView的问题,这部分工作正常。这是关于collectionView中的scrollView没有随着它上升。
我有一个固定在屏幕底部的视图,在该视图内我有一个 textView。固定在视图顶部的是一个固定在屏幕顶部的collectionView
-top of viewController
collectionView
containerView that contains a textView
-bottom of viewController
当点击 textView 的 textField 时,我会使用一个通知来检测键盘何时上升和下降。它工作正常,因为 collectionView 像它应该的那样上下波动。问题是collectionView 的内容。如果当collectionView 上升时collectionView 的单元格填满屏幕,它的scrollVIew 不会随之上升,因此单元格位于键盘后面。下面两张图。
当发送键盘通知时,我尝试更改 collectionView 的 contentInset、scrollIndicatorInsets,并尝试滚动到最后一个单元格,但什么也没有。单元格只是向上滚动一点。
@objc fileprivate func keyboardWillShow(notification: Notification) {
guard let keyboardDuration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else { return }
guard let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
let keyboardFrame = keyboardFrame.cgRectValue
let keyboardHeight = keyboardFrame.height
containerViewBottomAnchorConstraint?.isActive = false
containerViewBottomAnchorConstraint = containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -keyboardHeight)
containerViewBottomAnchorConstraint?.isActive = true
// I tried this
let item = tableData.count - 1
let indexPath = IndexPath(item: item, section: 0)
if !tableData.isEmpty {
collectionView.scrollToItem(at: indexPath, at: .bottom, animated: true)
}
// I tried this
let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: -keyboardHeight, right: 0)
collectionView.contentInset = contentInsets
collectionView.scrollIndicatorInsets = contentInsets
UIView.animate(withDuration: keyboardDuration, animations: {
self.view.layoutIfNeeded()
}) { [weak self](_) in
self?.autoScrollToLastCell() // I tried this
}
}
@objc fileprivate func keyboardWillHide(notification: Notification) {
guard let keyboardDuration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else { return }
containerViewBottomAnchorConstraint?.isActive = false
containerViewBottomAnchorConstraint = containerView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0)
containerViewBottomAnchorConstraint?.isActive = true
UIView.animate(withDuration: keyboardDuration, animations: {
self.view.layoutIfNeeded()
}) { [weak self](_) in
self?.autoScrollToLastCell()
}
}
func autoScrollToLastCell() {
let section = 0
let item = collectionView.numberOfItems(inSection: section) - 1
let index = IndexPath(item: item, section: section)
if item > 0 {
collectionView.scrollToItem(at: index, at: .bottom, animated: true)
}
}
【问题讨论】:
-
-keyboardHeight我觉得应该是正面的 -
嘿,谢谢。我已经试过了,但是没有用。
标签: ios swift uiscrollview uicollectionview keyboard-events