SoFunction
Updated on 2025-04-11

Swift uses CollectionView to achieve the ad bar sliding effect

This article shares the specific code for Swift to realize the sliding effect of the ad bar for your reference. The specific content is as follows

Create a class:

//cell reuse the identifierprivate let reuseIdentifier = "reuseIdentifier"
class PlayCollectionViewController: UICollectionViewController {

 //Number of pages private let pageCount = 6
 //Layout object (custom layout) private var layout: UICollectionViewFlowLayout = PlayLayout()

 init() {
  (collectionViewLayout: layout)
 }

 required init?(coder aDecoder: NSCoder) {
  fatalError("init(coder:) has not been implemented")
 }

 override func viewDidLoad() {
  ()

  //Register cell  collectionView?.registerClass(, forCellWithReuseIdentifier: reuseIdentifier)
 }

 //MARK: - UICollectionDataSource
 override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  return pageCount
 }

 override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

  let cell = (reuseIdentifier, forIndexPath: indexPath) as! NewfearureCell
   = 
  return cell
 }
}

Customize the cell of the CollectionView

//MARK: - Here we still customize collectionViewCell in (in the file)class NewfearureCell: UICollectionViewCell {

 //Save the image index private var imageIndex:Int? {
  didSet {
   //Create the image name according to the page number (the name of each image is only different with the most and most number)    = UIImage(named: "image_\(imageIndex!)")
  }
 }

 override init(frame: CGRect) {
  (frame: frame)

  //Initialize the UI  setupUI()
 }
 required init?(coder aDecoder: NSCoder) {
  fatalError("init(coder:) has not been implemented")
 }

 private func setupUI() {

  //Add child control to contentView  (iconView)
  //Layout subcontrol position (filling screen)  iconView.xmg_Fill(contentView)
 }

 //MARK: Lazy loading private lazy var iconView = UIImageView()
}

Inherit UICollectionViewFlowLayout, customize layout

private class PlayLayout: UICollectionViewFlowLayout {

 //Rewrite the system to prepare the layout override func prepareLayout() {

  //Set layout layout  itemSize = ().
  minimumInteritemSpacing = 0
  minimumLineSpacing = 0
  scrollDirection = 

  //Set other properties  collectionView?.showsHorizontalScrollIndicator = false
  collectionView?.bounces = false
  collectionView?.pagingEnabled = true
 }
}

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.