Swift3.0学习之CollectionView的简单使用

2017-07-17 by w350981132

1、设置layout

let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width:60,height: 80) //设置item尺寸 layout.minimumLineSpacing = (UIScreen.main.bounds.width - 240) * 0.2 //上下间隔 layout.minimumInteritemSpacing = (UIScreen.main.bounds.width - 240) * 0.1 //左右间隔 layout.headerReferenceSize = CGSize(width:0,height: 0) //头部间隔 layout.footerReferenceSize = CGSize(width:0,height: 0) //底部间隔 layout.sectionInset = UIEdgeInsetsMake(, , , ) //section四周的缩进 layout.scrollDirection = UICollectionViewScrollDirection.vertical //滚动方向

2、初始化collectionview

let myCollectionView = UICollectionView.init(frame: view.bounds, collectionViewLayout: layout) myCollectionView.delegate = self myCollectionView.backgroundColor = UIColor.white myCollectionView.dataSource = self myCollectionView.register(UINib.init(nibName: "XXXXXX", bundle: nil), forCellWithReuseIdentifier: "YYYYY") view.addSubview(myCollectionView)3、实现代理
func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 }
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return count }
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "xxxxxx", for: indexPath) as! XXCollectionViewCell return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { }

除了定义FlowLayout外的另外一种设定item的方法:

通过代理实现

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(10, 10, 10, 10) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 60, height: 80) }


最新更新:

第七城市

栏目导航(关闭)