我有UICollectionView,里面有单元格。除了一件事,一切都运行良好。
在键盘外观动画期间,即将离开屏幕的顶部单元格会消失在原地,没有任何动画 https://www.youtube.com/watch?v=hMt6DiJD5KU
我试图实现finalLayoutAttributesForDisappearingItem
但它没有任何效果。 还试图在layoutAttributesForElementsInRect
扩大矩形
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( 将目标文本字段滚动到视图中。
您需要注册键盘更改通知。 (键盘将隐藏通知和键盘将更改帧通知(
使用通知中心:
课堂内:
let notificationCenter = NotificationCenter.default
在视图中DidLoad:
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)
}
}
}
关闭键盘时重置内容内陷。 我正在使用文本字段委托方法。
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