2

I have spent a while scouring the internet but have not found a good solution. Basically the problem is, in my messagecollectionview (eg, like a list of messages on any app) I want a smart and smooth way of reloading the messages without messing with the UI of the view, and without requiring the using to drag up on the view. I have found a few solutions, such as

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView.contentOffset.y < 0 {
        self.loadMoreMessages()
    }
}

Or

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    if scrollView.contentOffset.y < -100 {
        self.loadMoreMessages()
    }
}

Or

func scrollview(_ scrollView: UIScrollView) {
    var visibleRect = CGRect()

    visibleRect.origin = self.messagesCollectionView.contentOffset
    visibleRect.size = self.messagesCollectionView.bounds.size
    let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)

    guard let indexPath = self.messagesCollectionView.indexPathForItem(at: visiblePoint) else { return }

    print(" \(indexPath)")
    if indexPath.section == 3 {
        self.loadMoreMessages()
    }
}

But all of these suffer from lagging or a poor user experience. I have looked for an article about this but cannot find one. Note, my loadMoreMessages is:

@objc func loadMoreMessages() {
    if channel.synchronizationStatus == .all {
        channel.messages?.getBefore(UInt(messages.count), withCount: self.FETCH_COUNT) { (result, items) in
            self.messages = self.messages.union(Set(items!))
            self.sortMessages()
            DispatchQueue.main.async {
                self.messagesCollectionView.reloadData()
                self.messagesCollectionView.reloadDataAndKeepOffset()
                self.refreshControl.endRefreshing()
            }
        }
    }
}

Thoughts on the matter would be great.

AlexK
  • 336
  • 8
  • 21
  • 41

0 Answers0