前端之家收集整理的这篇文章主要介绍了
Swift中用CollectionView做广告栏滑动效果,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
创建一个类:PlayCollectionViewController.swift
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()
collectionView?.registerClass(NewfearureCell.self,forCellWithReuseIdentifier: reuseIdentifier)
}
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
class NewfearureCell: UICollectionViewCell {
private var imageIndex:Int? {
didSet {
iconView.image = UIImage(named: "image_\(imageIndex!)")
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI() {
contentView.addSubview(iconView)
iconView.xmg_Fill(contentView)
}
private lazy var iconView = UIImageView()
}
继承UICollectionViewFlowLayout,自定义布局
private class PlayLayout: UICollectionViewFlowLayout {
override func prepareLayout() {
itemSize = UIScreen.mainScreen().bounds.size
minimumInteritemSpacing = 0
minimumLineSpacing = 0
scrollDirection = UICollectionViewScrollDirection.Horizontal
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.bounces = false
collectionView?.pagingEnabled = true
}
}