Shahnas Ettool
Shahnas Ettool

Reputation: 21

Animate auto image slide UIScrollView UIKit

How do I animate the auto slide of the images in the below code. I was unable to add animation to the UIScrollView. I want the slide to look smooth. Now it looks like someone is manually doing it even though its auto slide. I have few images added and has set the image to auto slide when there is more than one image. The auto slide is working properly with 3 sec interval. However, the sliding is not smooth.

class Banners: UITableViewCell, UIComponentProtocol {

func updateUI(_ layout: UIComponent) {
        componentLayout = layout
        pageControl.numberOfPages = actualBannerCount
        if layout.style.contains("MAX_HEIGHT") {
            bannerStyle = .maxHeight
        } else {
            bannerStyle = .minHeight
        }
        self.collectionView.reloadData()
        
        // Start the timer for auto-scrolling if there are multiple pages
        if pageControl.numberOfPages > 1 {
            startAutoScroll()
            // Scroll to the first real banner (index 1) after reloading
            DispatchQueue.main.async {
                self.collectionView.scrollToItem(at: IndexPath(item: 1, section: 0), at: .centeredHorizontally, animated: false)
            }
        } else {
            stopAutoScroll()
        }
    }

    @objc private func autoScroll() {
        let currentIndex = getCurrentIndex()
        let nextIndex = (currentIndex + 1) % (actualBannerCount + 2) // Wrap around using modulo
        let indexPath = IndexPath(item: nextIndex, section: 0)
        
        // Only scroll if the next index is valid
        if nextIndex < collectionView.numberOfItems(inSection: 0) {
            collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
        }
        
        // Update the page control
        pageControl.currentPage = (nextIndex - 1 + actualBannerCount) % actualBannerCount // Adjust for dummy items
    }
    
}

extension Banners: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offsetX = scrollView.contentOffset.x
        let width = scrollView.frame.width
        
        // When reaching the last dummy slide, reset to the first real slide
        if offsetX >= width * CGFloat(actualBannerCount + 1) {
            collectionView.contentOffset = CGPoint(x: width, y: 0)
        }
        
        // When reaching the first dummy slide, reset to the last real slide
        if offsetX <= 0 {
            collectionView.contentOffset = CGPoint(x: width * CGFloat(actualBannerCount), y: 0)
        }
        
        // Update the page control
        let currentIndex = Int((offsetX + width / 2) / width) - 1
        if currentIndex >= 0 && currentIndex < actualBannerCount {
            pageControl.currentPage = currentIndex
        }
    }
}

Upvotes: 0

Views: 29

Answers (0)

Related Questions