我有一個ViewController mycollectionview
並在其中創建一個UICollectionView collection view
並將大小設置爲幀大小。我有一個自定義UICollectionViewCell CollectionViewCell
類。圖像大小不同,我想同時顯示一個單元格(不滾動時)。 這裏是mycollectionview
代碼:UICollectionView垂直分頁與代碼目標-C
- (void)viewDidLoad
{
[super viewDidLoad];
imgnum = @[@"1.jpg",@"2.jpg",@"3.jpeg",@"4.jpg"];
UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
layout.itemSize = CGSizeMake(80.0, 80.0);
collectionview = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
collectionview.translatesAutoresizingMaskIntoConstraints = NO;
collectionview.delegate = self;
collectionview.dataSource = self;
collectionview.bounces = false;
[collectionview registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
[self.view addSubview:collectionview];
{
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CollectionViewCell *cell = [collectionview dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
cell.pic.image = [UIImage imageNamed:imgnum[indexPath.row%4]];
cell.lab.text = @"Eiffel";
return cell;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
float w = self.view.frame.size.width;
CGSize a = [UIImage imageNamed:imgnum[indexPath.row%4]].size;
float aspect = a.width/a.height;
return CGSizeMake(w, w * 1/aspect);
}
它是我CollectionViewCell
代碼:
- (void)initialize
{
_pic = [UIImageView new];
_pic.translatesAutoresizingMaskIntoConstraints=false;
[self.contentView addSubview:_pic];
_lab = [UILabel new];
_lab.textColor = [UIColor blackColor];
_lab.translatesAutoresizingMaskIntoConstraints = false;
[self.contentView addSubview:_lab];
}
我會推薦你不要使用這個CGSize a = [UIImage imageNamed:imgnum [indexPath.row%4]]。size;作爲圖像大小,如果超過設備框架高度,將會產生問題並將該單元展開爲可滾動。您希望一次顯示一個圖像,因此我可以將contentcell高度設置爲與設備高度或collectionview的框架相同。稍後設置UIImageview setContentMode:AspectFit,以便圖像適合一個單元格,並且在一段時間內可以適用於一個圖元的滾動。 –