學習iOS最多的控件是UITableView和UICollectionView践叠,只要做APP肯定離不開這兩個組件了啦膜,因為手頭上面在搞天氣預報的app刽虹,用到了UICollectionView,也希望在這次的知識梳理的過程中不斷深化知識译秦,也發(fā)現(xiàn)新的問題。
查看一下文檔,在iOS6之后,多出來了UICollectionView威根,基本上和UITableView的API差不多,都需要設置DataSource和Delegate.
在實際的使用中我們都會自定義我們自己的Cell视乐。那我們先簡單了解一下洛搀,結構。構成CollectionView分為3個結構:
Cell 單元格 顯示信息
SupplementaryViews 頁眉頁腳
Decoration Views 裝飾整個View
如果要實現(xiàn)CollectionView的話佑淀,基本需要實現(xiàn)`UICollectionViewDataSource`,`UICollectionViewDelegate`,`UICollectionViewDelegateFlowLayout`這三個協(xié)議,接下來就一一講解一下留美。
`UICollectionViewDataSource`:用于向Collection View提供數(shù)據(jù),有以下方法:
1.Section數(shù)目:
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
2.Section里面有多少item
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
3.提供Cell設置
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
UICollectionViewDelegate
:用于交互,有以下方法:
1.管理cell的高亮
optional func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool
optional func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath)
optional func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath)
2.管理cell的選擇
optional func collectionView(_ collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool
optional func collectionView(_ collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
optional func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAtIndexPath indexPath: NSIndexPath) -> Bool
UICollectionViewLayout
進行排版谎砾,布局的作用
1.定義每個UICollectionView 的大小
optional func collectionView(_collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
2.定義每個UICollectionView 的 margin
optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets
當你使用nib文件來設計Cell的時候逢倍,一定要記住的是,你對于他的樣式都發(fā)生了改變景图,否則沒必要使用nib文件较雕,這也是我最近一直沒搞懂什么時候使用nib文件,什么時候直接在 storyboard操作就可以了挚币。