将CollectionView内容移动到键盘上方

时间:2018-01-12 08:03:55

标签: ios swift uicollectionview

我想在键盘出现时将CollectionView Cells移动到键盘上方。我刚刚获得了键盘大小,然后我将UIEdgeInsets更改为Collection视图的底部但没有任何反应

override func viewDidLoad() {
        super.viewDidLoad()

    self.view.addSubview(collectionV)
    collectionV.dataSource = self
    collectionV.delegate = self
    collectionV.alwaysBounceVertical = true
    collectionV.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 45, right: 0)
    collectionV.backgroundColor = UIColor.white
    collectionV.keyboardDismissMode = .interactive

    NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardWillShow), name: .UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardWillHide), name: .UIKeyboardWillHide, object: nil)

}

@objc func handleKeyboardWillShow(notification: Notification) {
    print("will show?")

    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {

        let userInfo = notification.userInfo!
        let animationDuration: TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue

        ContainerViewBottomAnchor?.constant = -keyboardSize.height
        collectionV.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: keyboardSize.height+8, right: 0)

        UIView.animate(withDuration: animationDuration) {
            self.view.layoutIfNeeded()

        }
    }
}

@objc func handleKeyboardWillHide(notification: Notification) {

    print("will hide?")
    let userInfo = notification.userInfo!
    let animationDuration: TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue

    ContainerViewBottomAnchor?.constant = 0
    self.collectionV.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 45, right: 0)

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

在模拟器上,当我按(⌘k)它的工作(单元格移动到上面),但当我点击TextField显示键盘不工作(单元格不移动),我仍然得到(打印(&#) 34;将显示")),也在真实设备上不起作用。

这让我感到困惑,有什么帮助可以弄清楚这里有什么问题?

编辑修正: let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue

感谢@MichaelVorontsov

0 个答案:

没有答案