UICollectionView 圖片顯示空白的原因

最近在使用UICollectionView顯示圖片,使用過程中踩了幾個坑,不過最終解決掉了,如下:

使用方法,自定義CollectionViewCell,繼承自UICollectionViewCell,然後添加UIImageView進入CollectionViewCell。

第一個坑:
頭文件裏面定義UIImageView:
@property (strong, nonatomic) IBOutlet UIImageView *imageView
然後在storyboard裏面,拖入UIImageView進入CollectionViewCell,鏈接映射,結果沒有顯示圖片,debug跟蹤發現imageView屬性nil,猜測是storyboard加載時,這種方法沒有自動創建UIImageView對象,遂放棄這種方法,採用代碼生成UIImageView,方法如下:

頭文件裏面定義UIImageView:
@property (strong, nonatomic) UIImageView *imageView

.m文件裏面,initWithFrame裏面:
self.imageView = [[UIImageView alloc] initWithFrame:frame];
[self.contentView addSubview:self.imageView];
結果有的能顯示出來,有的顯示空白

第二個坑:self.imageView = [[UIImageView alloc] initWithFrame:frame];
上面使用了cell的frame,debug跟蹤發現,frame的x,y座標是cell的座標位置,再給UIImageView的話,會座標偏移,看不到UIImageView了
解決辦法有兩種,一是把x,y的值設爲0,二是直接設置爲self.contentView.bounds較爲省事
我這邊改爲:
self.imageView = [[UIImageView alloc] initWithFrame:self.contentView.bounds];
顯示正確。


總結:一是要自己寫代碼加入UIImageView進入cell的contentView,二是加入UIImageView時位置別設錯了。
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章