collection view 3

creating custom layouts

1:要繼承UICollectionViewLayout,這里面的方法核心任務是以下兩點:

# 指明滾動區(qū)域的尺寸。Specify the size of the scrollable content area.

# 提供attribute 對象(UICollectionViewLayoutAttributes)給cells和views,讓collection view能夠給它們指定位置和大小。


invalidateLayout和reloadData的區(qū)別:

invalidateLayout是要在必要時重新計算每個cell的UICollectionViewLayoutAttributes,也就是位置和大小的改變。

注意:記住,當調用invalidateLayout時,并不代表著馬上開始更新layout.這個方法僅僅標識這當前l(fā)ayout和數(shù)據(jù)是不匹配的,需要更新。當下一個view更新循環(huán)時,collection view會檢查它的layout是否過時,如果是就更新。事實上,你可以一連串的調用invalidateLayout方法,但并不是每一次都會更新。

reloadData:如果dataSource改變的話,就可以用這個。


以下三個方法是必須要實現(xiàn)的,它們提供了collection view所需要的主要信息。其它的方法有可能會用到,但這三個方法每次layout precess時都會按順序調用。

1:prepare() 做上前的計算,提供layout信息。

2:collectionViewContentSize ?在上個方法計算的基礎上得出所有內容的總體尺寸。

3:layoutAttributesForElementsInRect: ?在指定范圍里的所有cells和views的attributes


Creating Layout Attributes

當你要繼承UICollectionViewLayoutAttributes,必須要實現(xiàn) isEqual:方法,因為collection view有些動作要要用到這個方法。


Including Decoration Views in Your Custom Layouts

這個decoration views只是裝飾用的。它不像cell和supplementary,并不依賴data source.你可以用它提供自定義的背景,填充cells的周圍等等,就是裝飾用的。并不和數(shù)據(jù)交互。

當你要為decoration view 創(chuàng)建attribute時,記得要設置zIndex.它決定decoration view是否顯示在cell或supplementary view的前面或后面。


Making Insertion and Deletion Animations More Interesting

插入一個cell,會引起其它cells和views 布局的改變。即使,layout對象知道已存在cells和views的當前位置,但卻不知道,要插入cells的起始位置。插入時,collection view會詢問layout 對象,所有cells和views的初始位置(包括,被插入的。)用下面的方法實現(xiàn):

override func initialLayoutAttributesForAppearingItem(at itemIndexPath:IndexPath) ->UICollectionViewLayoutAttributes?

刪除操作和插入操作是類似的。要實現(xiàn)的方法是:

override func finalLayoutAttributesForDisappearingItem(at itemIndexPath:IndexPath) ->UICollectionViewLayoutAttributes?

官方文檔上說,當插入時collection view會問layout對象要這個插入的cell的初始屬性(就是開始位置的屬性,然后再動畫移到最終位置)。

注意:

Note:Listing 5-2would animate all cells when one is inserted, so the three cells that were already present before the fourth was inserted would also pop out from the center of the collection view. To animate only the cell being inserted, check to see if the index path of the item matches the index path of an item passed to theprepareForCollectionViewUpdates:method and only perform the animation if a match is found. Otherwise, return the attributes returned by calling thesupermethod ofinitialLayoutAttributesForAppearingItemAtIndexPath:.

當插入一個時,全部的cell都會動起來。所以在第四個插入時其它三個已經(jīng)存在的也會從collection view的中間出來。如果只有插入的cell動起來,可以在prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem])里查看,是否有匹配的indexPath,如果有就執(zhí)行動畫。否則就返回super的initialLayoutAttributesForAppearingItemAtIndexPath:.


> 注意:初始化和結束布局,attributes里的size不能為(0,0),不然動畫都不能成功

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容