Swift USES CollectionView to achieve the sliding effect of the advertising bar

  • 2020-06-12 10:47:03
  • OfStack

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

Create 1 class: PlayCollectionViewController.swift


//cell Reuse identifier 
private let reuseIdentifier = "reuseIdentifier"
class PlayCollectionViewController: UICollectionViewController {

 // The page number 
 private let pageCount = 6
 // The layout object ( Custom layout )
 private var layout: UICollectionViewFlowLayout = PlayLayout()

 init() {
  super.init(collectionViewLayout: layout)
 }

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

 override func viewDidLoad() {
  super.viewDidLoad()

  // registered cell
  collectionView?.registerClass(NewfearureCell.self, 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 = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewfearureCell
  cell.imageIndex = indexPath.item
  return cell
 }
}

Custom cell for CollectionView


//MARK: -  We're still here (PlayCollectionViewController.swift In the file ) The custom collectionViewCell
class NewfearureCell: UICollectionViewCell {

 // Save image index 
 private var imageIndex:Int? {
  didSet {
   // Create picture names based on page Numbers ( You need only the most and most names for each image 1 The number of different )
   iconView.image = UIImage(named: "image_\(imageIndex!)")
  }
 }

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

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

 private func setupUI() {

  // Add child controls to contentView
  contentView.addSubview(iconView)
  // Layout child control positions ( Fill the screen )
  iconView.xmg_Fill(contentView)
 }

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

Inherit from UICollectionViewFlowLayout and customize the layout


private class PlayLayout: UICollectionViewFlowLayout {

 // Overrides the way the system prepares the layout 
 override func prepareLayout() {

  // Set up the layout layout 
  itemSize = UIScreen.mainScreen().bounds.size
  minimumInteritemSpacing = 0
  minimumLineSpacing = 0
  scrollDirection = UICollectionViewScrollDirection.Horizontal

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

Related articles: