簡體   English   中英

當被稱為“太早”時,UICollectionViewFlowLayout的layoutAttributesForItemAtIndexPath返回nil

[英]UICollectionViewFlowLayout's layoutAttributesForItemAtIndexPath returns nil when called “too early”

我的設置:具有流布局的標准UICollectionView; 數據源設置為我的控制器。 在xib文件中按常規配置布局。 當我嘗試通過Controller的viewDidLoad方法中的layoutAttributesForItemAtIndexPath:訪問單元格的布局屬性時,如下所示:

NSLog(@"LayoutAttribute: %@", [self.collectionView.collectionViewLayout layoutAttributesForItemAtIndexPath: [NSIndexPath indexPathForRow:0 inSection:0]]);

輸出是

"LayoutAttribute: (null)"

即使布局具有為我提供正確布局屬性所需的所有信息。 它仍然無法在viewWillAppear:中工作,但是“神奇地”開始在viewDidAppear中工作:

"LayoutAttribute: <UICollectionViewLayoutAttributes: 0x8c4f710> index path: (<NSIndexPath 0x8c48be0> 2 indexes [0, 0]); frame = (0 0; 50 50);"

我發現了使它工作的非常奇怪的方法。 我只是在請求布局屬性之前訪問collectionViewContentSize:

NSLog(@"Layout content size: %@", NSStringFromCGSize(self.collectionView.collectionViewLayout.collectionViewContentSize));    
NSLog(@"LayoutAttribute: %@", [self.collectionView.collectionViewLayout layoutAttributesForItemAtIndexPath: [NSIndexPath indexPathForRow:0 inSection:0]]);

一直如預期的那樣輸出:

"Layout content size: {768, 50}"
"LayoutAttribute: <UICollectionViewLayoutAttributes: 0x8c4f710> index path: (<NSIndexPath 0x8c48be0> 2 indexes [0, 0]); frame = (0 0; 50 50);"

這里發生了什么? 我假設訪問內容大小會觸發布局中的某些內容,但是有人知道是否有適當的方法來執行此操作嗎? 還是這只是一個令人討厭的錯誤?

layoutAttributesForItemAtIndexPath:的文檔說,如果該索引路徑中沒有任何項目,則僅返回nil 在調用layoutAttributesForItemAtIndexPath:之前,您是否未在集合視圖上調用reloadData

另一個常見問題是調用鏈中的某些中間對象為nil 也許collectionView或collectionView.collectionViewLayout nil

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM