简体   繁体   中英

UICollectionView scrollToItem Not Working in iOS 14

I'm using a collection view, UICollectionView, and it works absolutely great...except that I cannot scroll to any particular item. It seems to always scroll to the "middle" is my best guess. In any case, whatever I send to scrollToItem seems to have no effect on the scrolling. I've put it in various locations throughout my view controller but with no success.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    let lastIndex = IndexPath(row: messages.count-1, section: 0)
    self.messagesView.scrollToItem(at: lastIndex, at: .bottom, animated: true)
}

UICollection View has bug in iOS 14 with scrollToItem . In iOS 14 it will only work if collection view paging will be desable. So i got a solution if we have to scroll with both manual and programatically.

Specially for iOS 14

  self.collView.isPagingEnabled = false
  self.collView.scrollToItem(at: IndexPath(item: scrollingIndex, section: 0), at: .left, animated: true)
  self.collView.isPagingEnabled = true

You could try putting the scrolling code in viewDidLayoutSubviews which should get called after all table cells are loaded, which means your messages.count should work. Also, make sure you only have a single section in your collection view.

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    self.scrollToBottom()
}

func scrollToBottom() {
    DispatchQueue.main.async {
        let lastIndex = IndexPath(item: messages.count-1, section: 0)
        self.messagesView.scrollToItem(at: lastIndex, at: .bottom, animated: true)
    }
}

Swift 5 / iOS 15

I was facing the same problem, so I tried this one-line code and get it done.

// here we slect the required cell instead of directly scrolling to the item and both work same. 

self.collectionView.selectItem(at: IndexPath(row: self.index, section: 0), animated: true, scrollPosition: .left)

This is what worked for me, in case you want paging enabled:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    collectionView.isPagingEnabled = false
    collectionView.scrollToItem(
        at: IndexPath(item: 1, section: 0),
        at: .centeredVertically,
        animated: false
    )
    collectionView.isPagingEnabled = true
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM