【问题标题】:scrollToItem isn't working in my CollectionView?scrollToItem 在我的 CollectionView 中不起作用?
【发布时间】:2018-11-29 12:11:36
【问题描述】:

为什么 scrollToItem 在我的 CollectionView 中不起作用?我想在EnabledID 上使用scrollToItem。那么是什么问题以及如何解决呢?

代码:

var dataArray = NSMutableArray() // dataArray is has a data from Database
var EnabledID = Int()

EnabledID = UserDefaults.standard.integer(forKey: "EnabledID")
    
if EnabledID == 0 {
        
    EnabledID = 1
    UserDefaults.standard.set(1, forKey: "EnabledID")
        
} else {
    if EnabledID < dataArray.count {
        let index = NSIndexPath(item: EnabledID, section: 0)
        self.myCollectionView.scrollToItem(at: index as IndexPath, at: .centeredVertically, animated: true)
    }
}
    

【问题讨论】:

标签: ios swift uicollectionview uiscrollview userdefaults


【解决方案1】:

试试这个代码...

[collectionView setDelegate:self];
[collectionView reloadData];
[collectionView layoutIfNeeded];
[collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];

斯威夫特 - 4.x

collectionView.delegate = self
collectionView.reloadData()
collectionView.layoutIfNeeded()
collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .top, animated: true)

当滚动方向为水平时,您需要使用leftrightcenteredHorizo​​ntally

top是垂直方向。

collectionView.scrollToItem(at: index, at: .top, animated: true)

【讨论】:

  • “当滚动方向为水平时,您需要使用 left、right 或 centeredHorizo​​ntally。” - 这条评论为我节省了一个小时。太感谢了! =D
【解决方案2】:

我发现这样做的最好方法是不使用 scrollToItem 而是获取索引的 CGRect 然后使其可见。

 let rect = self.collectionView.layoutAttributesForItem(at: IndexPath(row: 5, section: 0))?.frame
 self.collectionView.scrollRectToVisible(rect!, animated: false)

【讨论】:

    【解决方案3】:

    我的问题有点奇怪。我的 iPhone 6/7/8 工作正常,但 iPhone X 或 11 无法滚动到我预期的位置。 我的原始代码是:

    collectionView.reloadData()
    collectionView.scrollToItem(at: IndexPath(item: 10, section: 0), at: .top, animated: true)
    

    在我添加 collectionView.layoutIfNeeded() 之后。问题在我的 iPhone X 和 11 上得到解决。

    collectionView.reloadData()
    collectionView.layoutIfNeeded()
    collectionView.scrollToItem(at: IndexPath(item: 10, section: 0), at: .top, animated: true)
    

    这个答案的灵感来自@ram。他应该得到荣誉。添加这个答案只是为了强调不同iPhone之间的区别。这样人们就可以更快地搜索到他们的答案。

    【讨论】:

    • collectionView.layoutIfNeeded(),这节省了我的时间。谢谢
    【解决方案4】:

    它不起作用,因为 contentSize 可能是 (0,0)。 如果您不希望使用 layoutIfNeeded()(因为您可能会在那里执行一些不需要的和不必要的事情),您应该自己计算(假设您的数据已加载,并且视图进行了布局)。

    Swift 5.2

        collection.contentSize = CGSize(width: collection.bounds.width * CGFloat(items.count), height: collection.bounds.height)
        collection.scrollToItem(at: IndexPath(row: startingIndex, section: 0), at: .left, animated: false)
    

    【讨论】:

      【解决方案5】:

      试试这个水平集合视图

      var isViewDidLayoutCallFirstTime = true
      
      
      override func viewDidLayoutSubviews() {
          super.viewDidLayoutSubviews()
          guard self.isViewDidLayoutCallFirstTime else {return}
          self.isViewDidLayoutCallFirstTime = false
          self.collectionView.collectionViewLayout.collectionViewContentSize // It will required to re calculate collectionViewContentSize in internal method 
          let indexpath = IndexPath(item: self.currentIndex, section: 0)
      
          self.collectionView.scrollToItem(at: indexpath, at: UICollectionViewScrollPosition.centeredHorizontally, animated: false)
      
      }
      

      【讨论】:

        【解决方案6】:

        我在 iOS 14.x 和 Xcode 12.x 上遇到过这个问题。

        对我有用的解决方案是使用:

        collectionView.scrollRectToVisible(rect, animated: true)
        

        【讨论】:

          【解决方案7】:

          在我的情况下 .centeredVertically 没有任何效果,并且正在悄悄地失败。 .centeredHorizo​​ntally 固定它

          【讨论】:

            【解决方案8】:

            试试这个。它对我有用

            func scrollToIndex(index:Int) {
                 let rect = self.collectionView.layoutAttributesForItem(at:IndexPath(row: index, section: 0))?.frame
                 self.collectionView.scrollRectToVisible(rect!, animated: true)
             }
            

            【讨论】:

              【解决方案9】:
               var scrollImg: Int = 0
              
              override func viewDidLoad() {
                  super.viewDidLoad()
                  _ = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(autoScroll), userInfo: nil, repeats: true)
              
              }
              
                 @objc func autoScroll() {
                  
                  let totalCount = imageArray.count-1
                  
                  if scrollImg == totalCount{
                      scrollImg = 0
                  }else {
                      scrollImg += 1
                  }
                  
                  DispatchQueue.main.async {
                      let rect = self.listOfViewsCollectionViews.layoutAttributesForItem(at: IndexPath(row: self.scrollImg, section: 0))?.frame
                      if self.scrollImg == 0{
                          self.listOfViewsCollectionViews.scrollRectToVisible(rect!, animated: false)
                      }else {
                          self.listOfViewsCollectionViews.scrollRectToVisible(rect!, animated: true)
                      }
                  }
              }
              

              【讨论】:

                【解决方案10】:

                使用这个

                self.messageCV.reloadData()
                let indexPath = IndexPath(row: 0, section: 0)
                self.messageCV.scrollToItem(at: indexPath, at: .bottom, animated: true) // .top
                

                【讨论】:

                • 你确定你的代码是正确的吗??因为给我警告(值 'cell' 已定义但从未使用过;考虑用布尔测试替换,将 'let cell = self.myCollectionView.cellForItem(at: indexPath as IndexPath) 替换为?CollectionViewCell' 与 '(self.myCollectionView.cellForItem (at: indexPath as IndexPath) as?CollectionViewCell) != nil')。而你的条件if let cell = self.myCollectionView... 是空的!!
                • 使用此代码,因为在我的项目中同样的错误解决方案
                • 这个如果。条件只是检查
                • 我在控制台中检查并打印 (not able to cast collection view cell class to CollectionViewCell)
                • 你身边的collection view issue,outlet,添加类名,
                猜你喜欢
                • 1970-01-01
                • 2018-10-18
                • 2021-01-28
                • 2017-10-13
                • 1970-01-01
                • 2018-04-14
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多