【问题标题】:How to move up collection view controller when keyboard appears?键盘出现时如何向上移动集合视图控制器?
【发布时间】:2020-06-13 06:02:21
【问题描述】:

我有一个在情节提要中创建的集合视图和一个容器视图,其中文本字段以编程方式限制在视图的底部。但是,当我显示键盘时,集合视图会隐藏在下面,我不知道该怎么做。我看了看,大多数答案都说在键盘通知侦听器中使用 self.view.frame.origin.y 但这对我不起作用。

我的键盘通知代码

    @objc func keyboardWillShow(notification: NSNotification) {
        let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
        let duration = ((notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue)!
        
        containerViewbottomAnchor?.constant = -keyboardFrame!.height

        
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
        
    }

第一张图片是正常聊天,第二张是显示键盘时可以看到的最大视图。容器视图包含我以编程方式添加的文本字段和按钮。它们位于输入附件视图中,以便在键盘出现时更新它们的位置。

【问题讨论】:

  • containerViewbottomAnchor 是什么?
  • 并在此函数中记录 keyboardFrame ... 确保您获得了身高
  • 你能用这个解决方案检查一下吗stackoverflow.com/a/56802182/7301439
  • 我编辑了原件以显示更多容器视图的图片

标签: ios swift xcode


【解决方案1】:

您是否尝试过此解决方案? https://stackoverflow.com/a/57438748/13042987

NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)


@objc func handleKeyboardWillShow(notification: Notification) {

        collectionView.scrollToItem(at: IndexPath(row: messagesList.count - 1, section: chatSection), at: .top, animated: false)
}

【讨论】:

  • '@objc func handleKeyboardDidShow() { if messages.count > 0 { let indexPath = NSIndexPath(item: messages.count - 1, section: 0) collectionView.scrollToItem(at: indexPath as IndexPath, at: .top, animated: true) } }' 是的,这适用于将用户带到底部,但键盘仍然重叠
【解决方案2】:

我设法通过更改为 UICollectionview 控制器类来修复它

【讨论】:

    猜你喜欢
    • 2018-05-21
    • 2015-11-29
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 2014-02-07
    相关资源
    最近更新 更多