【问题标题】:Scrolling UICollectionView in response to keyboard notification滚动 UICollectionView 以响应键盘通知
【发布时间】:2017-03-10 06:04:44
【问题描述】:

我正在构建一个信使应用程序。

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

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是指位于屏幕底部或键盘框架顶部的消息输入文本字段)

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

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

【问题讨论】:

    标签: ios swift autolayout uicollectionview core-animation


    【解决方案1】:

    如果您希望在完成中编写的代码块与键盘按下同时发生,那么您不应该在完成块中编写它。 您可以在调用具有持续时间的动画之前使用 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})
    
        }
    }
    

    【讨论】:

    • 我需要 ScrollView 在我的键盘出现时也移动,所以我使用了上述答案的一个版本:** DispatchQueue.main.async { self.scrollToBottomAnimated(animated: true) } **
    猜你喜欢
    • 2013-03-08
    • 2021-08-17
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多