自动键盘滚动不起作用

时间:2017-08-06 21:43:22

标签: ios swift uicollectionview uitextfield

我有一个collectionViewController和一个inputContainerAccesoryView,里面有一个uitextfield。每当我按下键盘上的返回时,一个项目(一行)被添加到集合视图中,我希望集合视图自动滚动到它的底部;我也希望当键盘出现时,它也会滚动到集合视图的底部。我有一个尝试过的代码,但不是按照我想要的方式滚动。如果你能看出来......

viewDidLoad中

collectionView?.keyboardDismissMode = .interactive

    NotificationCenter.default.addObserver(
        self,
        selector: #selector(HomeViewController.keyboardWillShow(event:)),
        name: NSNotification.Name.UIKeyboardWillShow,
        object: nil
    )

textFieldShouldReturn

handleKeyboardDidShow()

方法

func keyboardWillShow(event: Notification) {
    //let keyboardqlq = inputTextField.frame.height
    guard let keyboardFrame = (event.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
    guard let colelctionview = self.collectionView else { return }

    colelctionview.contentInset.bottom = keyboardFrame.height - 200
    colelctionview.scrollIndicatorInsets.bottom = keyboardFrame.height - 200

    // do NOT scroll messages if the keyboard is the `accessoryView`
    if keyboardFrame.height != inputContainerView.frame.height {
        handleKeyboardDidShow()
    }
}


func handleKeyboardDidShow() {

    if messages.count > 0 {
        let indexPath = IndexPath(item: messages.count - 1, section: 0)
        collectionView?.scrollToItem(at: indexPath, at: .bottom, animated: true)
    }
}

先谢谢!!!

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。可能它效率不高但它解决了我的问题。确保textfield委托是自己的。

 var needToScroll :Bool = true

func textFieldDidBeginEditing(_ textField: UITextField) {
        needToScroll = true
    }
func handleKeyboardWillHide(notification:Notification) {
    let keyboardDuration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? Double

    UIView.animate(withDuration: keyboardDuration!) {
        self.view.layoutIfNeeded()
             self.chatLogCollectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 30, right: 0)

        self.needToScroll = false
    }

}
func handleKeyboardWillShow(notification:Notification) {

    let keyboardFrame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect
     let keyboardDuration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? Double

    UIView.animate(withDuration: keyboardDuration!) {
        self.view.layoutIfNeeded()
        self.chatLogCollectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: (keyboardFrame?.height)!, right: 0)


        if self.needToScroll {
            if self.chatLogCollectionView.messages.count > 0 {

                self.chatLogCollectionView.scrollToItem(at: NSIndexPath(item: self.chatLogCollectionView.messages.count - 1, section: 0) as IndexPath, at: .bottom, animated: false)
            }
        }

    }

    }