如何在用户点击InputAccessoryView时滚动到CollectionView的底部



我有一个评论部分在我的应用程序中,用户可以1)看到所有的评论已经发布和2)张贴自己的评论在同一个视图控制器。当用户到达视图控制器时,视图保留在CollectionView的顶部,在那里显示最早的注释。然而,当用户点击底部的自定义InputAccessoryView时,我希望视图控制器滚动到CollectionView的底部,那里有最新的注释。这就是我挣扎的地方。

My CommentVC看起来像这样:

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)
    }
}
如您所见,我已经创建了函数scrollToBottom,但它不工作调用这个函数在一个textFieldDidBeginEditing函数,即使我子类CommentVC与UITextFieldDelegate。这在CommentInputAccessoryView中也不起作用因为scrollToBottom应该需要在CommentVC中调用。更复杂的是,实际的UITextView有自己的文件CommentInputTextView在CommentInputAccessoryView文件中使用。

我不知道这个问题的正确解决方案是什么,但如果有人能提出建议,我将不胜感激。

您在哪里调用scrollToBottom方法?如果您希望在用户点击inputAccessoryView时调用该方法,那么考虑添加一个UITapGesturer,如下所示:

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
}()

不要忘记在声明scrollToBottom之前添加@objc装饰符

最新更新