【问题标题】:How to scroll to the bottom of a CollectionView when the user taps the InputAccessoryView当用户点击 InputAccessoryView 时如何滚动到 CollectionView 的底部
【发布时间】:2021-01-16 04:29:01
【问题描述】:

我的应用中有一个评论部分,用户可以在其中 1) 查看所有已发布的 cmets,以及 2) 在同一个视图控制器中发表自己的评论。当用户到达视图控制器时,视图仍保留在 CollectionView 的顶部,其中显示了最早的 cmets。但是,当用户点击底部的自定义 InputAccessoryView 时,我希望视图控制器滚动到最新 cmets 所在的 CollectionView 底部。这就是我苦苦挣扎的地方。

我的 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,但即使我使用 UITextFieldDelegate 子类化 CommentVC,在 textFieldDidBeginEditing 函数中调用此函数也不起作用。这在 CommentInputAccessoryView 文件中也不起作用,因为 scrollToBottom 应该需要在 CommentVC 中调用。更复杂的是,实际的 UITextView 有自己的名为 CommentInputTextView 的文件,该文件在 CommentInputAccessoryView 文件中使用。

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

【问题讨论】:

    标签: ios swift uitextfield uitextfielddelegate inputaccessoryview


    【解决方案1】:

    你在哪里调用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 装饰器

    【讨论】:

    • 感谢您的回复。我调用 scrollToBottom 方法的唯一地方是在一个函数中发布评论(所以你可以在发布后在底部看到它),而没有其他地方。我尝试了您添加点击手势识别器(并创建 @objc scrollToBottom 方法)的建议,但不幸的是这并没有奏效。还有其他解决这个问题的想法吗?
    • 我解决了 - 这不是您提出的建议,但它帮助我思考了这个问题,所以谢谢。我添加了一个 NotificationCenter 观察者,它会在 UITextView 开始编辑时向下滚动到底部,这与被点击的 UITextView 相同。
    猜你喜欢
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    相关资源
    最近更新 更多