雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

Swift

當前位置:主頁 > 軟件編程 > Swift >

Swift使用CollectionView實現(xiàn)廣告欄滑動效果

來源:本站原創(chuàng)|時間:2020-01-11|欄目:Swift|點擊:

本文實例為大家分享了Swift實現(xiàn)廣告欄滑動效果的具體代碼,供大家參考,具體內(nèi)容如下

創(chuàng)建一個類:PlayCollectionViewController.swift

//cell重用標識
private let reuseIdentifier = "reuseIdentifier"
class PlayCollectionViewController: UICollectionViewController {

 //頁面?zhèn)€數(shù)
 private let pageCount = 6
 //布局對象(自定義布局)
 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()

  //注冊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
 }
}

自定義CollectionView的cell

//MARK: - 在這里我們依然在(PlayCollectionViewController.swift的文件中)自定義collectionViewCell
class NewfearureCell: UICollectionViewCell {

 //保存圖片索引
 private var imageIndex:Int? {
  didSet {
   //根據(jù)頁碼創(chuàng)建圖片名字(需要每張圖片的名稱只有最有最有一個數(shù)不同)
   iconView.image = UIImage(named: "image_\(imageIndex!)")
  }
 }

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

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

 private func setupUI() {

  //添加子控件到contentView
  contentView.addSubview(iconView)
  //布局子控件位置(填充屏幕)
  iconView.xmg_Fill(contentView)
 }

 //MARK: 懶加載
 private lazy var iconView = UIImageView()
}

繼承UICollectionViewFlowLayout,自定義布局

private class PlayLayout: UICollectionViewFlowLayout {

 //重寫系統(tǒng)準備布局的方法
 override func prepareLayout() {

  //設置layout布局
  itemSize = UIScreen.mainScreen().bounds.size
  minimumInteritemSpacing = 0
  minimumLineSpacing = 0
  scrollDirection = UICollectionViewScrollDirection.Horizontal

  //設置其他屬性
  collectionView?.showsHorizontalScrollIndicator = false
  collectionView?.bounces = false
  collectionView?.pagingEnabled = true
 }
}

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持我們。

上一篇:Swift解決UITableView空數(shù)據(jù)視圖問題的簡單方法

欄    目:Swift

下一篇:Swift中優(yōu)雅處理閉包導致的循環(huán)引用詳解

本文標題:Swift使用CollectionView實現(xiàn)廣告欄滑動效果

本文地址:http://www.jygsgssxh.com/a1/Swift/11924.html

網(wǎng)頁制作CMS教程網(wǎng)絡編程軟件編程腳本語言數(shù)據(jù)庫服務器

如果侵犯了您的權利,請與我們聯(lián)系,我們將在24小時內(nèi)進行處理、任何非本站因素導致的法律后果,本站均不負任何責任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權所有