SoFunction
Updated on 2025-04-11

Swift achieves unlimited carousel effects

Starting today, my focus of learning has begun to shift to Swift, and I will share some of my own learning experiences. What I bring to you today is unlimited carousels. Unlimited carousel of ad pages is a very common feature. Most APPs have it, and most programmers have implemented it. Today we will use Swift to implement it. Project gallery

The basic controls we can choose for image switching are two UIScrollView and UICollectionView. This time we choose UICollectionView; since it is a carousel, we will use Timer. Therefore, the main knowledge points we applied this time are UICollectionView and Timer;

import UIKit

class CycleScrollView: UIView, UICollectionViewDelegate,UICollectionViewDataSource {

  var bottomView : UICollectionView?
  var width : CGFloat?
  var height : CGFloat?
  var timer : Timer?
  
  override init(frame: CGRect){
    
    (frame: frame)
    // 1. Set background color     = 
    // 2. Set width and height    width = 
    height = 
    // 3. Add bottomView    setupBottomView()
    // 4. Add timer    setupTimer()
  }
  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
  
  
  func setupBottomView() {
    
    // 5. Set the layout of the collectionView    let flowLayout = UICollectionViewFlowLayout();
     = 
     = 0;
     = 0;
     = ;
    bottomView = (frame: , collectionViewLayout: flowLayout)
    (bottomView!);
    // 6. Set the size of the collectionView    bottomView?.contentSize = CGSize(width:width! * CGFloat(4),height:height!)
    // 7. Pagination    bottomView?.isPagingEnabled = true
    // 8. Remove the scrollbar    bottomView?.showsVerticalScrollIndicator = false
    bottomView?.showsHorizontalScrollIndicator = false
    // 9. Set up a proxy    bottomView?.delegate = self
    bottomView?.dataSource = self
    // 10. Register cell    bottomView?.register(UICollectionViewCell().classForCoder, forCellWithReuseIdentifier: "ID");
    if #available(iOS 10.0, *) {
      // 11.Preload      bottomView?.isPrefetchingEnabled = true
    } else {
      // Fallback on earlier versions
    }
  }
  func setupTimer() {
    // 12. Instantiate the timer    timer = (timeInterval: 2, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true);
    (timer!, forMode: );

    (deadline: () + 2) {
    
      ?.fire();
    }
  }
  func timerAction() {
    
    var contentOffsetX = (?.)! + 
    
    if contentOffsetX >  * 3 {
      // When the current view is displayed with the third one, set the offset of bottomView to 0      ?.contentOffset = CGPoint(x:0,y:0)
      contentOffsetX = 
    }
     ?.setContentOffset(CGPoint(x:contentOffsetX,y:0), animated: true)
  }
  // Rewrite the removeFromSuperview method to delete the timer, otherwise the timer will always exist, wasting memory  override func removeFromSuperview() {
    
    timer?.invalidate()
    timer = nil
    ()
  }
  // Mark:UICollectionViewDataSource
  // Set Times  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    
    return 4;
  }
  // Set cell  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
    let cell : UICollectionViewCell = (withReuseIdentifier: "ID", for: indexPath)
    for view : UIView in  {
      
      ()
    }
    let imageView = (frame: )
    if  < 3 {
      
       = (named: String())

    } else {
       = (named: String(0))
    }
    (imageView)
    
    return cell;
  }
  // Mark:UICollectionViewDelegate
  // Click method  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    
    print("You clicked on \( == 3 ? 0 : ) indivual");
  }
  
}

UICollectionView and Timer are basically the same as OC. The UI parts of Swift and OC should be consistent, because the underlying layer is OpenGL. Let me just talk about the difference:

: If repeated, OC waits for an interval before executing, Swift is executed immediately, so I used GCD to turn on the timer.

No CGPointZero.

The principle of infinite carousel is to add one more itme that is the same as the first one at the end. When you slide to the last itme, set the contentOffset of the UICollectionView and continue to move to the right. If not added, it will give the user a feeling of lag.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.