我有带单元格的UICollectionView。除了一件事之外,一切都正常。
在键盘外观动画过程中,即将离开屏幕的顶部单元格消失在原地,而没有任何动画https://www.youtube.com/watch?v=hMt6DiJD5KU
我试图实现finalLayoutAttributesForDisappearingItem
,但没有任何效果。
还尝试在layoutAttributesForElementsInRect
中扩展rect
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let rect = CGRect(x: rect.minX, y: rect.midY - 312, width: rect.width, height: rect.height + 312)
return itemAttributesCache.filter { $0.frame.intersects(rect) }
}
但也没有运气
我发现的唯一可行的解决方案是将屏幕上方的
UICollectionView.frame
扩展到键盘高度,并将UICollectionView.contentInset.top
设置为键盘高度。它有效,但绝对难看。任何想法如何解决?
最佳答案
要在您的收藏夹视图中显示正确的键盘,请执行以下操作:
1)获取键盘的大小。
2)通过键盘高度调整集合视图的底部内容插图。
3)将目标文本字段滚动到视图中。
您需要注册以获取键盘更改通知。
(keyboardWillHideNotification和keyboardWillChangeFrameNotification)
使用通知中心:
内部 class :
let notificationCenter = NotificationCenter.default
在viewDidLoad中:
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name:NSNotification.Name.UIKeyboardWillHide, object: nil)
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
@objc func adjustForKeyboard(notification: Notification) {
if let keyboardValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let keyboardScreenEndFrame = keyboardValue.cgRectValue
let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)
if notification.name == NSNotification.Name.UIKeyboardWillHide {
collectionView.contentInset = .zero
} else {
collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height - view.safeAreaInsets.bottom, right: 0)
}
}
}
取消键盘后,重置内容插图。
我正在使用textField委托方法。
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
print("returned")
textField.resignFirstResponder()
return true
}
有关更多详细信息,请参阅以下链接:
https://developer.apple.com/library/archive/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html
和
https://www.hackingwithswift.com/example-code/uikit/how-to-adjust-a-uiscrollview-to-fit-the-keyboard