【问题标题】:UICollectionView top cells disappear while animating keyboard appearanceUICollectionView 顶部单元格在动画键盘外观时消失
【发布时间】:2020-04-09 03:17:19
【问题描述】:

我有 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 设置为键盘高度。它有效,但绝对丑陋。

有什么解决办法吗?

【问题讨论】:

  • finalLayoutAttributesForDisappearingItem 被调用用于对应于从集合视图中移除的项目的单元格,而不是用于离开屏幕的单元格。如果您可以提供一个示例项目,其中包含布局实现和发生的问题,将会更容易为您提供帮助。
  • 您是否使用任何 SDK(如 IQKeyboardManager)来处理您的键盘操作?

标签: ios objective-c swift uicollectionview uicollectionviewlayout


【解决方案1】:

要在您的收藏视图中显示正确的键盘外观:

1) 获取键盘大小。

2) 通过键盘高度调整collection view的底部内容插入。

3) 将目标文本字段滚动到视图中。

您需要注册键盘更改通知。 (keyboardWillHideNotification 和keyboardWillChangeFrameNotification)

使用通知中心:

课内:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 2023-03-25
    • 2012-11-01
    • 2018-09-23
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多