ios - 如何在swift 4中滚动到 Collection View 中的特定索引?

标签 ios uicollectionview swift4 uicollectionviewcell uicollectionviewdelegate

我已经搜索了与此问题相关的各种链接,但无法解决此问题,这就是我发布此问题的原因。我有一个 collectionView .在一个特定的单元格中,我有很多 View ,例如 用户资料查看 , 产品查看 , 评论框查看 等在评论框查看 有一个文本查看 用户可以在其中键入然后发表评论。发表评论后,我想滚动那个特定的单元格,用户从哪个单元格发布了评论。我知道我必须使用 self.collectionView.scrollToItem(at:IndexPath(item: indexNumber, section: sectionNumber), at: .right, animated: false)
这是代码,

func customCell(_ cell: UICollectionViewCell, didPressButton: UIButton, indexPathRow: Int, commentPost: String, commentatorImage: UIImageView, commentatorName: UILabel, comments: UITextView) {
    DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: {
        self.collectionView.reloadData()
        self.postComment(commentatorImage: commentatorImage, commentatorName: commentatorName, comments: comments) })
}

但我的问题是:
  • 我必须在哪里编写此代码?在 View 中确实出现了?或在
    评论发帖功能在哪里成功是真的?
  • 如何将 indexNumber 和 sectionNumber 传递给
    self.collectionView.scrollToItem(at:IndexPath(item: indexNumber, section:sectionNumber)

  • 请任何人帮助我解决这个问题。谢谢

    最佳答案

    您可以使用其中一种生命周期方法,甚至可以在重新加载数据调用之后使用。像这样的东西,

    override func viewDidLayoutSubviews() 
    {
        super.viewDidLayoutSubviews()
        let indexPath = IndexPath(item: 12, section: 0)
        self.collectionView.scrollToItem(at: indexPath, at: [.centeredVertically,   .centeredHorizontally], animated: true)
    }
    

    谢谢。

    关于ios - 如何在swift 4中滚动到 Collection View 中的特定索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51355680/

    相关文章:

    ios - 我如何正确地重新加载我的 UICollectionView 的数据?

    ios - 推送 UIViewController 时实例成员不能在类型上使用

    arrays - Swift 4 按值复制数组

    swift - 如何转换 [String : Any] to [NSAttributedStringKey : Any]

    ios - 滚动到 UICollectionView 中的下一个单元格

    ios - UITableViewCell 子类不允许我设置标签文本

    ios - SwiftUI如何知道将哪个environmentObject分配给哪个变量

    objective-c - UIImageView 实现

    ios - 在 Swift 中使用 CollectionView 进行网格布局

    ios - 由于 RealmSwift,当 swift 3 @obj 推理设置为 "default"时,应用程序崩溃