How to scroll to the bottom of a CollectionView when the user taps the InputAccessoryView

109 Views Asked by At

I have a comment section in my app where a user can 1) see all of the comments that have been posted and 2) post a comment of his own in the same view controller. When the user arrives at the view controller, the view remains at the top of the CollectionView where the earliest comments are displayed. However, when the user taps on the custom InputAccessoryView at the bottom, I'd like the view controller to scroll to the bottom of the CollectionView where the latest comments are located. This is where I'm struggling.

My CommentVC looks something like the following:

lazy var containerView: CommentInputAccessoryView = {
    
    let frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 60)
    let containerView = CommentInputAccessoryView(frame: frame)
    containerView.backgroundColor = .white
    containerView.delegate = self
    return containerView
}()

override var inputAccessoryView: UIView? {
    get {
        return containerView
    }
}

override var canBecomeFirstResponder: Bool {
    return true
}

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

As you can see, I've created the function scrollToBottom, but it doesn't work to call this function within a textFieldDidBeginEditing function even if I subclass CommentVC with a UITextFieldDelegate. And this also won't work in the CommentInputAccessoryView file since scrollToBottom would supposedly need to called in CommentVC. Complicating matters further is that the actual UITextView has its own file named CommentInputTextView which is used in the CommentInputAccessoryView file.

I'm not sure what the right solution to this problem would be, but would appreciate it if someone can chime in with a suggestion.

1

There are 1 best solutions below

2
Luca Sfragara On

Where are you calling scrollToBottom method? If you want that method to be called when the users taps on inputAccessoryView, then consider adding a UITapGesturer like this:

lazy var containerView: CommentInputAccessoryView = {

let frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 60)
let containerView = CommentInputAccessoryView(frame: frame)
containerView.backgroundColor = .white
containerView.delegate = self
let tap = UITapGestureRecognizer(target: self, action #selector(self.scrollToBottom))
containerView.addGestureRecognizer(tap)

return containerView

}()

And don't forget to add the @objc decorator before the declaration of scrollToBottom