每次用都要搜索一圈相关用法,实在是不胜其烦,这里记录一下.
定义好Identifier
private let cellReuseIdentifier = "tagCollectionViewCell"
private let headerReuseIdentifier = "headerReuseIdentifier"
UICollectionViewFlowLayout
collectionView的布局样式类,这个玩意设置的灵活得多,不仅仅是布局,还可以实现很多奇特的效果,这里关注基本用法,在此就不再赘述.
初始化
let layout = UICollectionViewLayout()
let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
注册headerview和cell
collectionView.registerNib(UINib.init(nibName: "TeaFriendsTagCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: cellReuseIdentifier)
collectionView.registerClass(headerView.classForCoder, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerReuseIdentifier)
相关协议
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout
相关代理
collectionView datasource:
//数据的数量
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 0
}
//sections数量
func numberOfSectionsInCollectionView(collectionView:UICollectionView) ->Int {
return 0
}
collectionView delegate:
//点击cell
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
}
CollectionView DelegateFlowLayout:
//headerview的Size
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSizeMake(ScreenWidth, 80 * HEIGHT_SCALE)
}
//这里是headerview
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionHeader {
headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: headerReuseIdentifier, forIndexPath: indexPath) as! TagHeaderCollectionReusableView
headerView.pagedView.delegate = self
return headerView
}else {
return UICollectionReusableView()
}
}
//cell的Size
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let w = (ScreenWidth - 30)/2
return CGSizeMake(w, w)
}