本文實例為大家分享了Swift實現廣告欄滑動效果的具體代碼,供大家參考,具體內容如下
創建一個類:PlayCollectionViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
//cell重用標識 private let reuseIdentifier = "reuseIdentifier" class PlayCollectionViewController: UICollectionViewController { //頁面個數 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
//MARK: - 在這里我們依然在(PlayCollectionViewController.swift的文件中)自定義collectionViewCell class NewfearureCell: UICollectionViewCell { //保存圖片索引 private var imageIndex:Int? { didSet { //根據頁碼創建圖片名字(需要每張圖片的名稱只有最有最有一個數不同) 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,自定義布局
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
private class PlayLayout: UICollectionViewFlowLayout { //重寫系統準備布局的方法 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 } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/weixin_34354945/article/details/87150895