数据源
var dataSource = [String]() //添加数据 privatefuncsaveData() { dataSource += ["A-1","A-2","A-3","A-4","A-5","A-6","A-7","A-8","A-9","A-10","A-11"] print(dataSource) }
collectionView懒加载
//懒加载 lazyvarcollectionView :UICollectionView = { let collLayou = UICollectionViewFlowLayout() letmag :CGFloat=10.0 letcount :CGFloat=5.0 letweight = (ScreenWidth-(mag*(count+1)))/count collLayou.itemSize=CGSize(width:weight, height:35) //行间距 collLayou.minimumInteritemSpacing = 5 //列间距 // collLayou.minimumLineSpacing = 10 collLayou.sectionInset=UIEdgeInsetsMake(10,10,10,10) letcoll =UICollectionView(frame:self.view.bounds, collectionViewLayout: collLayou) coll.backgroundColor = UIColor.white returncoll }()
添加到view中,遵守协议,注册cell
self.view.addSubview(self.collectionView) self.collectionView.delegate = self self.collectionView.dataSource = self self.collectionView.register(SwiftCollectionViewCell.classForCoder(), forCellWithReuseIdentifier:"cell") saveData()
实现协议方法
funccollectionView(_collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) ->UICollectionViewCell{ letcell = collectionView.dequeueReusableCell(withReuseIdentifier:"cell", for: indexPath)as!SwiftCollectionViewCell cell.backgroundColor = UIColor.blue print(dataSource[indexPath.item]) cell.lable.text=dataSource[indexPath.item] returncell; } funccollectionView(_collectionView:UICollectionView, numberOfItemsInSection section:Int) ->Int{ return dataSource.count } funcnumberOfSections(in collectionView:UICollectionView) ->Int{ return1; } funccollectionView(_collectionView:UICollectionView, didSelectItemAt indexPath:IndexPath) { print(indexPath.item) }