ios - 滚动 UICollectionView 以响应键盘通知

标签 ios swift autolayout uicollectionview core-animation

我正在构建一个 Messenger 应用。

我目前的键盘通知功能如下:

func handleKeyboardNotification(notification: NSNotification) {

        if let userInfo = notification.userInfo {
            let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue()
            print(keyboardFrame)


            let isKeyboardShowing = notification.name == UIKeyboardWillShowNotification


            bottomConstraint?.constant = isKeyboardShowing ? -keyboardFrame!.height : 0



            UIView.animateWithDuration(0, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {

                self.view.layoutIfNeeded()
                }, completion: { (completed) in

                    if isKeyboardShowing {
                        let indexPath = NSIndexPath(forItem: self.messages!.count - 1, inSection: 0)
                        self.collectionView?.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Bottom, animated: true)
                    }

            })

    }
}

(bottomConstraint.constant 是指位于屏幕底部或键盘框架顶部的消息输入文本字段)

但是,我希望完成参数中的操作与键盘打开同时发生,而不是在键盘打开之后发生。目前,当我关闭键盘时,它似乎可以自动布局,但当我打开它时却不行。

到目前为止,我尝试了很多方法都无济于事。 有什么建议吗?

最佳答案

如果您希望在完成中编写的代码块与键盘按下同时发生,那么您不应该将其写入完成 block 中。 您可以在调用带持续时间的动画函数之前使用 dispatch_async,这样它就可以同时工作:

   func handleKeyboardNotification(notification: NSNotification) {

            if let userInfo = notification.userInfo {
                let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue()
                print(keyboardFrame)


                let isKeyboardShowing = notification.name == UIKeyboardWillShowNotification


                bottomConstraint?.constant = isKeyboardShowing ? -keyboardFrame!.height : 0

DispatchQueue.main.async {
    if isKeyboardShowing {
                    let indexPath = NSIndexPath(forItem: self.messages!.count - 1, inSection: 0)
                            self.collectionView?.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Bottom, animated: true)
}


            UIView.animateWithDuration(0, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {self.view.layoutIfNeeded()}, completion: nil})

    }
}

关于ios - 滚动 UICollectionView 以响应键盘通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42711382/

相关文章:

ios - 在自动布局中动态更改 UIScrollView 的大小

iphone - 应用程序在较低版本的 iPhone 中崩溃

iphone - 如何使用 Storyboard在 iOS 中的 UIViewController 之间切换

swift - 在 Swift 中减少循环期间的内存使用

ios - UICollectionViewFlowLayoutminimumLineSpacing 不适用于整个 Collection View - Swift

swift - 扩展到通用结构,其中元素是通用结构

ios - 如何在不更改导航栏色调的情况下更改底部工具栏色调颜色?

ios - swift 5 : index out of range when returning the array count from tableView numberOfRowsInSection

ios - 模糊效果子层不会随着 xib 消失

iphone - iOS 应用程序无法在 iOS 6 或更低版本上运行