//
// ViewController.swift
// CollectionView_test
//
import UIKit
private let CollectionCellId = "CollectionCell"
class ViewController: UIViewController {
//懒加载 collectionView
fileprivate lazy var collectionView : UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: CustomFlowLayout())
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(collectionView)
collectionView.frame = view.bounds
collectionView.backgroundColor = UIColor(red: 244/255.0, green: 244/255.0, blue: 244/255.0, alpha: 1)
collectionView.dataSource = self;
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: CollectionCellId) //注册cell
}
}
//MARK:- UICollectionViewDataSource
extension ViewController : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 100;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionCellId, for: indexPath)
let R = (arc4random() % 256)
let G = (arc4random() % 256)
let B = (arc4random() % 256)
cell.backgroundColor = UIColor(red: CGFloat(R)/255, green: CGFloat(G)/255, blue: CGFloat(B)/255, alpha: 1.0)
return cell
}
}
//MARK:- 自定义流水布局
class CustomFlowLayout: UICollectionViewFlowLayout {
//重写 prepare()方法
override func prepare() {
super.prepare()
itemSize = CGSize(width: 120 , height: 120)
minimumLineSpacing = 2 //行间距
minimumInteritemSpacing = 2 //列间距
scrollDirection = .horizontal //滚动方向
collectionView?.isPagingEnabled = true //设置分页效果
collectionView?.showsHorizontalScrollIndicator = false //隐藏水平滚动条
}
}
效果图.png
网友评论